今天将从前篇介绍的模组做延伸,继续稍微深入研究模组的一些眉眉角角。
在我们前篇有提到一个重点,不晓得大家是否记得呢?
在模组中,state预设为模组区域变数,而actions/mutations/getters预设为全域变数
那如果今天我们想要把 actions/mutations/getters
改成区域变数,可以吗?可以唷!
什麽是带命名的空间模组呢?就是把 actions/mutations/getters
改成模组内区域变数,本来可以全域使用的 actions
就会变成A模组底下的 actions
罗!为什麽要这样做呢?
试想今天我们要统计次数(Count
),不太可能只有一个 Count
需要统计吧?
如果今天是需要统计点击次数,又需要统计购买次数呢?
那就可能会在两个模组的 mutations
中都有 updateCount
,这样重复命名不就头大了,所以需要将模组变成带命名的空间模组,避免此尴尬状况发生,也让模组具有更高的封装度和复用性。
export default {
namespaced: true,
}
store/count.js
内容如下:
export default {
namespaced: true,
state: {
count: 0
},
mutations: {
ADD_COUNT (state) {
state.count += 1
}
},
actions: {
updateCount (context, status) {
context.commit('ADD_COUNT', status)
}
}
}
一样与主档案 store/index.js
绑定
import countModules from './count'
export default new Vuex.Store({
modules: {
countModules
}
})
那在Vue元件中要如何使用带命名的空间模组count的actions呢?
只要将命名模组的名称插入就可以罗。
原本this.$store.dispatch('updateCount')
变成:
export default {
methods: {
updateCount () {
this.$store.dispatch('countModules/updateCount')
}
},
}
getters
部分:
全域内容的 rootState
和 rootGetters
会作为第三和第四参数传入 getter
,如以下范例,使用rootGetters
可以得到全域的 someOtherGetter
,没有使用的话就是得到此模组 moduleA
自己本身的 someOtherGetter
export default {
namespaced: true,
getters: {
someGetter (state, getters, rootState, rootGetters) {
getters.someOtherGetter // -> 'moduleA/someOtherGetter'
rootGetters.someOtherGetter // -> 'someOtherGetter'
},
someOtherGetter: state => { ... }
},
}
actions
部分:
全域内容的 rootState
和 rootGetters
上面提过就不提罗,比较特别的是 dispatch
或 commit
,若需要在全局命名空间内分发 action
或提交 mutation
,将 { root: true }
作为第三参数传给 dispatch
或 commit
即可。
export default {
namespaced: true,
actions: {
someAction ({ dispatch, commit, getters, rootGetters }) {
getters.someGetter // -> 'moduleA/someGetter'
rootGetters.someGetter // -> 'someGetter'
dispatch('someOtherAction') // -> 'moduleA/someOtherAction'
dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'
commit('someMutation') // -> 'moduleA/someMutation'
commit('someMutation', null, { root: true }) // -> 'someMutation'
},
someOtherAction (ctx, payload) { ... }
}
}
今天我们对模组有了更深一些的认识啦!非常开心,可喜可贺!
明天我们再来补充一些些细节的东西罗!
<<: 11.移转 Aras PLM大小事- 汇出 Mutiple Level BOM
Q1. Graph 是什麽 Graph 定义:一个 graph 由 数个点( vertex )与数个...
本篇介绍如何使用 infracost 工具估计 infrastructure apply 的花费 课...
想请教一下大家, 我想由 Site A LAN 连线到 Site B LAN, 环境简介如下: //...
这应该也是学习深度学习时的基础课程, 不确定跟图像分类比,哪一个会先学到, 但是在接触深度学习框架时...
上一章是在讲跟 Input 相关的表单元件会使用 TextField 来给定表单会用到的 requ...