對於NEW
按鈕的第一操作 - 生成組件 - 我們添加mutation
我們store.js
mutations: {
addJob (state) {
state.jobs.push(state.jobs.length + 1)
...
}
其次,創建本地模塊。這裏我們將使用reusableModule
來生成一個模塊的多個實例。爲了方便,我們將這個模塊保存在單獨的文件中。另外,請注意使用函數聲明模塊狀態。
const state =() => {
return {
count: 0
}
}
const getters = {
count: (state) => state.count
}
const mutations = {
updateCountPlus (state) {
state.count++
}
}
export default {
state,
getters,
mutations
}
要使用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
從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
和actions
。爲什麼不使用{mapGetters}
或{mapMutations}
?當我們有幾個模塊,並且我們知道需要模塊的路徑時,我們可以做到。不幸的是,我們無法訪問模塊名稱。
代碼在組件的模塊執行時(當您的應用程序 引導時)運行,而不是在組件創建時運行。因此,只有在您知道模塊名稱之前,才能使用這些幫助程序 。
這裏沒有什麼幫助。我們可以分開我們的getters
和mutations
,然後將它們作爲對象導入並保持清潔。
<script>
import computed from '../store/moduleGetters'
import methods from '../store/moduleMutations'
export default {
props: ['id'],
computed,
methods
}
</script>
返回到App
組件。我們必須承諾我們的mutation
,並讓我們爲App
創建一些getter
。展示如何訪問位於模塊中的數據。
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>