由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
src
├── store
│ ├── modules
│ │ ├── user.js
│ │ └── login.js
│ ├── getters.js
│ └── index.js
└── main.js
main.js 使用store import store from "./store";
/*
* Copyright © 2020 LiuDanYang. All rights Reserved.
*/
import Vue from "vue";
import App from "./App";
import store from "./store";
import router from "./router";
Vue.config.productionTip = false;
new Vue({
el: "#app",
router,
store,
render: (h) => h(App),
});
index.js
/*
* Copyright © 2020 LiuDanYang. All rights Reserved.
*/
import Vue from "vue";
import Vuex from "vuex";
import getters from "./getters";
import user from './modules/user';
import login from './modules/login';
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
user,
login,
},
getters,
});
export default store;
getters.js
/*
* Copyright © 2020 LiuDanYang. All rights Reserved.
*/
const getters = {
users: (state) => state.user.users,
token: (state) => state.login.token,
};
export default getters;
user.js (示例中使用的接口请根据项目实际情况使用)
/*
* Copyright © 2020 LiuDanYang. All rights Reserved.
*/
import { getUserInfo } from "@i/user";
const state = {
users: {},
};
const mutations = {
SET_USERS: (state, data) => {
state.users = data;
},
};
const actions = {
/**
* 获取用户信息
* @param commit
* @returns {Promise}
*/
getUserInfo({ commit }) {
return new Promise((resolve, reject) => {
getUserInfo().then((res) => {
const { status, data } = res;
if (status === "1") {
commit("SET_USERS", data);
resolve(data);
} else {
reject(res);
}
});
});
},
};
export default {
namespaced: true,
state,
mutations,
actions,
};
login.js (示例中使用的接口请根据项目实际情况使用)
/*
* Copyright © 2020 LiuDanYang. All rights Reserved.
*/
import { getLogin } from "@i/user";
import { getToken, setToken } from "@u/auth";
const state = {
token: getToken(),
};
const mutations = {
SET_TOKEN: (state, token) => {
state.token = token;
},
};
const actions = {
/**
* 用户登录
* @param commit
* @param data
* @returns {Promise}
*/
getLogin({ commit }, data) {
const { username, password} = data;
return new Promise((resolve, reject) => {
getLogin({
phonenumber: username.trim(),
password: password,
})
.then((res) => {
const { status, data } = res;
if (status === "1") {
commit("SET_TOKEN", data.token);
setToken(data.token);
resolve(res);
} else {
reject(res);
}
})
.catch((res) => {
reject(res);
});
});
},
};
export default {
namespaced: true,
state,
mutations,
actions,
};
页面使用示例
{{ users.name }}
参考文档:Module