目录
1. store/index.ts
2. main.ts
3. App.vue调用
4. 如果删除moduleA的namespaced属性, 保留moduleB的namespaced:true
5. 则App.vue修改为:
注意: 需要使用时带上模块名称的namespaced必须为true, 不写或者为false时调用时不需要写模块名称(获取state的值必须加模块名)
import { createStore } from "vuex";
// A模块
const moduleA = {
namespaced: true,
state: {
name: "moduleA",
},
getters: {
newName(state) {
return state.name;
},
},
mutations: {
changeName(state, payload) {
state.name = payload;
},
updateAge(state, playLoad) {
state.age = playLoad;
},
},
actions: {
changeAge({ commit }, age) {
setTimeout(() => {
commit("updateAge", age);
}, 0);
},
},
};
// B模块
const moduleB = {
namespaced: true,
state: {
name: "moduleB",
age: 33,
},
getters: {
newName(state) {
return state.name;
},
},
mutations: {
changeName(state, payload) {
state.name = payload;
},
updateAge(state, playLoad) {
console.log("playLoad", playLoad);
state.age = playLoad;
},
},
actions: {
changeAge(ctx, count) {
console.log("触发了-模块B的action");
setTimeout(() => {
ctx.commit("updateAge", count);
}, 1000);
},
},
};
export default createStore({
// 分模块
modules: {
moduleA,
moduleB,
},
});
import { createApp } from "vue";
import App from "./App.vue";
import * as Vue from "vue";
import store from './store';
const app = createApp(App);
app.use(store);
app.mount("#app");
姓名:
年龄:
模块a:
姓名(state): {{ store.state.moduleA.name }}
姓名(getters): {{ store.getters["moduleA/newName"] }}
年龄: {{ store.state.moduleA.age }}
模块b:
姓名:
年龄:
姓名(state): {{ store.state.moduleB.name }}
姓名(getters): {{ store.getters["moduleB/newName"] }}
年龄: {{ store.state.moduleB.age }}
import { createStore } from "vuex";
// A模块
const moduleA = {
state: {
name: "moduleA",
},
getters: {
newName(state) {
return state.name;
},
},
mutations: {
changeName(state, payload) {
state.name = payload;
},
updateAge(state, playLoad) {
state.age = playLoad;
},
},
actions: {
changeAge({ commit }, age) {
setTimeout(() => {
commit("updateAge", age);
}, 0);
},
},
};
// B模块
const moduleB = {
namespaced: true,
state: {
name: "moduleB",
age: 33,
},
getters: {
newName(state) {
return state.name;
},
},
mutations: {
// 更改数据函数
changeName(state, payload) {
state.name = payload;
},
updateAge(state, playLoad) {
console.log("playLoad", playLoad);
state.age = playLoad;
},
},
actions: {
changeAge(ctx, count) {
setTimeout(() => {
ctx.commit("updateAge", count);
}, 1000);
},
},
};
export default createStore({
// 分模块
modules: {
moduleA,
moduleB,
},
});
姓名:
年龄:
模块a:
姓名(state): {{ store.state.moduleA.name }}
姓名(getters): {{ store.getters["newName"] }}
年龄: {{ store.state.moduleA.age }}
模块b:
姓名:
年龄:
姓名(state): {{ store.state.moduleB.name }}
姓名(getters): {{ store.getters["moduleB/newName"] }}
年龄: {{ store.state.moduleB.age }}