Vuex中文官网传送门
目录结构如下:
其中vuex相关的三个文件counts.js、 index.js、 operate.js,内容如下:
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import counter from './counter.js'
import operate from './operate.js'
Vue.use(Vuex)
const state = {
name: 'zhaoyh'
}
const getters = {
getName (state) {
return state.name
}
}
const mutations = {
changeName (state, payload) {
state.name = `${
state.name} ${
payload}`
}
}
const actions = {
changeNameAsync (context, payload) {
return new Promise((resolve, reject) => {
setTimeout(() => {
context.commit('changeName', payload)
}, 1000)
})
}
}
const store = new Vuex.Store({
state,
getters,
mutations,
actions,
modules: {
counter,
operate
}
})
export default store
counter.js
// 模块内方法调用本模块内的方法和数据
const state = {
counterName: 'module > counter > zhaoyh'
}
const getters = {
// state, getters: 本模块内的state, getters
// rootState, rootGetters: 根模块/根节点内的state, getters
// rootState, rootGetters: 同时也包括各个模块中的state 和 getters
getCounterName (state, getters, rootState, rootGetters) {
// rootState.name
// rootState.counter.counterName
// rootState.operate.operateName
console.log(rootState)
// rootGetters.getName,
// rootGetters['counter/getCounterName']
// rootGetters['operate/getOperateName']
console.log(rootGetters)
return state.counterName
}
}
const mutations = {
changeCounterName (state, payload) {
state.counterName = `${
state.counterName} ${
payload}`
}
}
const actions = {
// context 与 store 实例具有相同方法和属性 ------ important!!!
// context 包括: dispatch, commit, state, getters, rootState, rootGetters
changeCounterNameAsync (context, payload) {
return new Promise((resolve, reject) => {
setTimeout(() => {
context.commit('changeCounterName', payload)}, 1000)
})
}
}
export default {
// 注意此处是namespaced,而不是names