您的位置:首页 > 产品设计 > UI/UE

基于vue-cli的vue项目之vuex的使用4-------moudles分块

2017-09-22 09:13 751 查看
按照官方文档,就是为了避免代码太长了。所以使用了moudle

1.store.js//配置仓库,第五道第二十六为一个模块。第二十七到四十八为一个模块,在第四十九到五十四行抛出
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const moudlesa = {
namespaced:true,
state: {
count: 0
},
mutations: {
incrementa(state, n) {
console.log(n);
state.count += n.amout;
}
},
actions: {
incrementa(context, m) {
setTimeout(() => {
context.commit({
type: "incrementa",
amout: m.amout
})
}, 1000)
}
}
}
const moudlesb = {
namespaced:true,
state: {
count: 0
},
mutations: {
incrementb(state, n) {
console.log(n);
state.count += n.amout;
}
},
actions: {
incrementb(context, m) {
setTimeout(() => {
context.commit({
type: "incrementb",
amout: m.amout
})
}, 1000)
}
}
}
const store = new Vuex.Store({
modules: {
a: moudlesa,
b: moudlesb

}

})
//export default store;
export default store;

2.main.js//配置store的路径,在第六十九行使用store
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './vuex/store';
Vue.config.productionTip = false;
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: {
App
},
})

3app.vue//在组件中使用//在第九十到第九十六提交a模块的数据,第九十七到一百零二行提交b模块的数据
<template>
<div id="app">
<img src="./assets/logo.png">
<button @click="clickme">点击调用commit</button>
<button @click="clickme1">点击调用dispatch</button>
<span>{{$store.state.a.count}}</span><span>{{$store.state.b.count}}</span>
</div>
</template>
<script>
export default {
name: 'app',
data() {},
methods: {
clickme: function() {
this.$store.commit({
type: "a/incrementa",
amout: 180
});
alert(this.$store.state.a.count)
},
clickme1: function() {
this.$store.dispatch({
type: "b/incrementb",
amout: 180,
});
}
},
}
</script>
<style>
</style>

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息