对于第一次操作NEW
按钮 -生成组件- 我们增加mutation
to our store.js
mutations: {
addJob (state) {
state.jobs.push(state.jobs.length + 1)
...
}
Second, 创建本地模块。这里我们要使用reusableModule
生成模块的多个实例。为了方便起见,我们将该模块保存在单独的文件中。还,注意使用函数来声明模块状态.
const state = () => {
return {
count: 0
}
}
const getters = {
count: (state) => state.count
}
const mutations = {
updateCountPlus (state) {
state.count++
}
}
export default {
state,
getters,
mutations
}
To use reusableModule
我们导入它并应用动态模块注册。
store.js
import module from './reusableModule'
const {state: stateModule, getters, mutations} = module
export const store = new Vuex.Store({
state: {
jobs: []
},
mutations: {
addJob (state) {
state.jobs.push(state.jobs.length + 1)
store.registerModule(`module${state.jobs.length}`, {
state: stateModule,
getters,
mutations,
namespaced: true // making our module reusable
})
}
}
})
之后,我们将链接Hello.vue
及其存储。我们可能需要state
, getters
, mutations
, actions
from vuex
。要访问存储,我们需要创建我们的getters
。与相同mutations
.
Home.vue
<script>
export default {
props: ['id'],
computed: {
count () {
return this.$store.getters[`module${this.id}/count`]
}
},
methods: {
updateCountPlus () {
this.$store.commit(`module${this.id}/updateCountPlus`)
}
}
}
</script>
想象一下我们有很多getters
, mutations
and actions
。为什么不使用{mapGetters}
or {mapMutations}
?当我们有多个模块并且我们知道所需模块的路径时,我们就可以做到这一点。不幸的是,我们无权访问模块名称。
该代码在执行组件的模块时运行(当您的应用程序
正在启动),而不是在创建组件时。所以这些助手可以
仅当您提前知道模块名称时才使用。
这里几乎没有帮助。我们可以分开我们的getters
and mutations
然后将它们作为对象导入并保持干净。
<script>
import computed from '../store/moduleGetters'
import methods from '../store/moduleMutations'
export default {
props: ['id'],
computed,
methods
}
</script>
回到App
成分。我们必须承诺我们的mutation
让我们创建一些getter
for App
。展示我们如何访问位于模块中的数据。
store.js
export const store = new Vuex.Store({
state: {
jobs: []
},
getters: {
jobs: state => state.jobs,
sumAll (state, getters) {
let s = 0
for (let i = 1; i <= state.jobs.length; i++) {
s += getters[`module${i}/count`]
}
return s
}
}
...
完成代码在App
成分
<script>
import Hello from './components/Hello'
import {mapMutations, mapGetters} from 'vuex'
export default {
components: {
Hello
},
computed: {
...mapGetters([
'jobs',
'sumAll'
])
},
methods: {
...mapMutations([
'addJob'
])
}
}
</script>