vuex中的store分模塊管理,需要在store的index.js中引入各個模塊,為了解決不同模塊命名沖突的問題,將不同模塊的namespaced:true,可以實現分離模板間的獨立。
使用舉例如下:
定義一個peopleInfo模塊,定義了state,actions,mutatios等
import { getUserInfo } from "@/api/userController"
const peopleInfo = {
namespaced: true, // 模塊化分離
state: {
name: 'chen'
},
actions: {
GetUserInfo ({ commit }) {
return new Promise((resolve, reject) => {
getUserInfo().then((res) => {
const data = res.data
commit('changeNameFun', data.userName)
resolve(data)
}).catch(err => {
reject(err)
})
})
},
},
mutations: {
changeNameFun (state, val) {
state.name = val
}
},
}
export default peopleInfo
在store的入口文件引入該模塊:
...... import peopleInfo from './peopleInfo.js' ........ const store = new Vuex.Store({ state, getters, mutations, modules: { peopleInfo } }) export default stores
用模塊中定義的state,getters,actions,mutations時,store操作.模塊名.執行動作
比如:this.$store.state.peopleInfo.name, this.$store.commit("peopleInfo/mutations'','wang'), this.$store.dispatch('peopleInfo/actions')等等
參考文章:https://blog.csdn.net/fuck487/article/details/83411856