13. 使用vuex管理状态
13.1. 下载依赖包
npm install vuex
13.2. vuex的多模块编程
- vuex单模块问题:
- 需要的管理状态数据比较多, 那对应的mutations/actions模块就会变得比较
- 如果添加新的数据管理, 需要修改现在文件(不断向其添加内容)
- vuex多模块编程:
- 对各个功能模块的数据分别进行管理, 这样更加具有扩展性
- 什么时候需要用vuex多模块编程?
13.3. store/modules/home.js
import {reqBaseCategoryList} from '@/api'
const state = {
baseCategoryList: [],
xxx: 'abc',
yyy: 123
}
const mutations = {
RECEIVE_BASE_CATEGORY_LIST(state, list) {
state.baseCategoryList = list
}
}
const actions = {
async getBaseCategoryList({ commit }) {
const result = await reqBaseCategoryList();
if (result.code === 200) {
commit('RECEIVE_BASE_CATEGORY_LIST', result.data)
}
},
}
const getters = {
}
export default {
state,
actions,
mutations,
getters
}
13.5. store/modules/user.js
export default {
state: {
userInfo: {}
},
actions: {},
mutations: {},
getters: {}
}
13.6. store/modules/index.js
import home from './home'
import user from './user'
export default {
home,
user
}
13.7. store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules'
Vue.use(Vuex)
export default new Vuex.Store({
modules,
})
13.8. 注册store
import store from './store'
new Vue({
store,
})