VueX分了模块如何使用
1、创建一个js文件,命名为ad的一个VueX的子模块
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const ad= ({
namespaced: true, //定义命名空间,防止冲突
state: {
adStyleShow : true
},
mutations: {
setAdStyleShow (state,flag) {
state.adStyleShow = flag
},
}
})
export default ad
2、然后再index.js中引入该子模块
import Vue from 'vue'
import Vuex from 'vuex'
import ad from './module/ad'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
ad
}
})
3、然后在Vue组件使用,首先如何获取state里面的值,有两种方法
//法一:直接用$store返回
computed:{
show(){
return this.$store.state.ad.adStyleShow //show为该vue组建中的变量名,ad为VueX模块的名字,adStyleShow为state里的值
}
}
//法二:用mapState映射
import { mapState} from "vuex"
computed:{
...mapState({
show : state=> state.ad.adStyleShow //show为该vue组建中的变量名,ad为VueX模块的名字,adStyleShow为state里的值
})
}
这两种方法都可以得到show的值为ad模块中state的adStyleShow值
4、如何使用mutations
<template>
<button @click="adStyleChange"></button>
</template>
<script>
import { mapState, mapMutations } from "vuex"
methods: {
...mapMutations("ad",["setAdStyleShow"]), //映射ad模块中的Mutations的setAdStyleShow方法
adStyleChange(){
this.setAdStyleShow(false)
}
}
</script>