Vue中UI组件库之Vuex与虚拟服务器初识(10)
./www/index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <div id="app"></div> </body> <script type="text/javascript" src="public/all.js"></script> </html>
./www/app/App.vue:
<template>
<div>
<h1>counter的{{$store.state.counterStore.a}}</h1>
<h1>taobao的{{$store.state.taobaoStore.a}}</h1>
<button @click="add">触发counter的ADD</button>
</div>
</template>
<script>
export default {
methods:{
add(){
//根据命名空间发出异步
this.$store.dispatch("counterStore/ADD")
}
}
}
</script>
./www/app/main.js:[
import Vue from "vue";
import App from "./App.vue";
import store from "./store";
new Vue({
el: "#app",
store,//引入store文件夹中的index.js
render: (h) => h(App)
})
./www/app/store/index.js:
import Vue from "vue";
import Vuex from "vuex";
import counterStore from "./counter/store.js";//引入counter的store
import taobaoStore from "./taobao/store.js";//引入taobao的store
import createLogger from 'vuex/dist/logger';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {//放入modules
counterStore,
taobaoStore
},
plugins : [createLogger()]
})
./www/app/store/counter/store.js:
export default {
namespaced: true, //命名空间
state : {
a:100
},
mutations : {
ADD(state,payload){
state.a++//上面的state
}
},
actions : {
ADD({commit}){
commit("ADD")//调用上面mutations的ADD
}
}
}
./www/app/store/taobao/store.js:
export default {
namespaced: true,//开启命名空间跟上面一样的用法
state : {
a:200
},
mutations : {},
actions : {}
}
五、配置虚拟服务器
一般情况下,一个应用的数据都需要等待后端接口人员开发完对应的接口才可以获取到,这样子的效率有点低。最好是我们可以自己模拟接口数据,进行页面的数据填充,打通所有关节,之后等接口开发好了,改下接口地址就好了。
所以,作为前端和客户端开发人员,在后端还没有给出对应的api接口时,我们无法做测试。
这时,我们可以使用json-server快速搭建一个测试的api接口,能在几十秒之内搭建好。
json-server 它能模拟“数据库”,提供了一套简单的API(RESTFUL)接口。
在开发过程中,前后端不论是否分离,接口多半是滞后于页面开发的。所以建立一个RESTFUL风格的API接口,给前端页面提供虚拟的数据,是非常有必要的。
