Vuex实现模块化步骤
- 创建模块文件:在项目合适目录(如
store/modules
)下,为每个功能模块创建单独的JavaScript文件,例如user.js
、product.js
等。
- 定义模块:在模块文件中,按照Vuex模块的结构定义状态、 mutations、actions、getters等。例如在
user.js
中:
const state = {
userInfo: null
}
const mutations = {
SET_USER_INFO(state, info) {
state.userInfo = info
}
}
const actions = {
async fetchUserInfo({ commit }) {
// 模拟异步请求获取用户信息
const response = await someApiCall()
commit('SET_USER_INFO', response.data)
}
}
const getters = {
getUserInfo(state) {
return state.userInfo
}
}
export default {
state,
mutations,
actions,
getters
}
- 引入并注册模块:在
store/index.js
中引入并注册这些模块。
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import product from './modules/product'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
user,
product
}
})
通过命名空间解决命名冲突
- 开启命名空间:在模块定义时,添加
namespaced: true
。例如在user.js
模块中:
const state = {
userInfo: null
}
const mutations = {
SET_USER_INFO(state, info) {
state.userInfo = info
}
}
const actions = {
async fetchUserInfo({ commit }) {
// 模拟异步请求获取用户信息
const response = await someApiCall()
commit('SET_USER_INFO', response.data)
}
}
const getters = {
getUserInfo(state) {
return state.userInfo
}
}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
- 使用命名空间访问:
<template>
<div>
{{ $store.state.user.userInfo }}
</div>
</template>
- **组件中提交mutation**:
this.$store.commit('user/SET_USER_INFO', { name: 'John' })
- **组件中分发action**:
this.$store.dispatch('user/fetchUserInfo')
- **获取getter**:
this.$store.getters['user/getUserInfo']