vuex的辅助技能
modules
上篇讲解的vuex举的例子都是只有一个或者几个状态。但是如果我们有很多个组件,他们都要有很多个状态怎么办?挤在一个store.js未免太过臃肿。所以vuex提供了modules的辅助技能。
modules用法
假如我们有三个组件,分别是human,cat,dog。那么我们分别创建三个js文件用来存放三个组件所需要的state状态等
首先,创建与main.js同级的文件夹store用来存放各组件的store.js文件。然后里面再分别创建三个组件对应的store文件。
分别是:cat_store.js,dog_store.js与human_store.js
// cat_store.js,dog_store.js的内容与human_store.js一样
// human_store.js
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)
export default {
state:{
...
},
getters:{
...
},
mutations:{
...
},
actions:{
...
}
}
其次,再store文件夹中创建index.js文件引入各组件的store文件
import Vue from 'vue'
import vuex from 'vuex'
import human_store from 'human_store.js'
import cat_store from 'cat_store.js'
import dog_store from 'dog_store.js'
Vue.use(vuex)
export default new vuex.Store({
modules: {
modules1(自定义命名): human_store,
modules2(自定义命名): cat_store,
modules3(自定义命名): dog_store
}
})
使用了modules之后,以human_store.js为例
调用state
this.&store.state.human_store.xxx
调用getters
this.&store.getters.human_store.xxx
调用mutations
this.&store.commit(‘xxx’) //不变
mapState、mapGetters、mapActions
有没有想过,如果我们很多个组件都用到state中的某个值,那我们岂不是要在每个组件中都要写上
this.&store.state.xxxx
这岂不是比我们使用data中的值更加繁琐?vuex的初衷不是这样的啊,应该是简洁明了的啊,这时mapXXXX诞生了
比如mapState
一般情况下,我们不想在同一个组件每次使用state的值时都这样
this.&store.state.xxxx
那么我们会通过computed
...
computed:{
xxxx(){
return this.&store.state.xxxx
},
yyyy(){
return this.&store.state.yyyy
}
}
...
但是如果我们有很多个状态值,每个都这样写的话岂不是很多很复杂?这时我们可以使用mapState
import { mapState } from 'vuex'
...
computed:{
...mapState({
xxx:state=>state.modules1.xxx
yyy:state=>state.modules1.yyy
})
}
...
这样就可以集中简便的管理。
mapActions有更简便的写法:
...
methods:{
...mapActions([
'xxx',
'yyy',
....
])
}
...
这种写法前提是,组件的methods中没有与’xxx’,’yyy’等相同的名字,并且store中的actions中也必须要有’xxx’,’yyy’等名字的方法
思考:为什么mapState举例的用法不可以这样用,而mapActions可以呢?
因为用了modules后,我们每次调用state,getters时都还要标明它是出自哪个modules的,但是actions却不用。上一篇写mutations时有提到,commit一个notShow,不管在哪个模块,只要有notShow都会被调用!
mapGetters、mapActions 的用法和 mapState 类似 , mapGetters 一般也写在 computed 中 , mapActions 一般写在 methods 中。