vuex的多模块使用
目录结构
|-store
|–index.js
|–modules
|–a.js
|–b.js
1、在a.js中声明单页所需要的数据等
const state = {
count:1
}
const mutations = {
add(state){
state.count++;
}
}
const actions = {
addAction({commit}){
commit('add')
}
}
export defult {
namespaced:true,
state,
mutations
actions
}
2、同样声明b.js
3、在index.js中进行导入
import Vue from 'vue';
import Vuex from 'vuex'
//导入单页store
import a from './modules/a'
import b from './modules/b'
Vue.use(Vuex);
//导出实例
export default new Vuex.Store({
modules:{
a,
b
}
})
4、在main.js 中导入声明的index.js中的store
import store from './store/index'
new Vue({
...
store
}).$mount('#app');
5、在a.vue中的使用
5.1利用全局变量使用数据
{{$store.state.a.count}}
5.2利用mapState
import {mapState} from 'vuex';
computed:{
...mapState('a',["count"])
},
5.3使用mutations
import {mapMutations} from 'vuex';
methods:{
...mapMutations('a',[
'add'
]),
},
5.4 使用actions
import {mapActions} from 'vuex'
methods:{
...mapMutations([ // 未使用命名空间
'add','reduce'
]),
...mapActions('a',['addAction'])
},
修改vuex中的值,做到全局传递
1、在module中新建c.js
const state = {
model: {
path: '',
isShow: false
}
}
const mutations = {
setModel (state, model) {
state.model = model
}
}
const actions = {
setModel ({ commit }, model) {
commit('setModel', model)
}
}
在页面文件中
import { mapActions } from 'vuex'
export default {
name: '',
data () {
return {
model: {
path: 'xx',
isShow: true
}
}
},
methods: {
...mapActions('c',['setModel'])
showModel () {
this.setModel(this.model)
}
}
}