模块不开启命名空间时,会共享全局命名空间。
{ state:{ ‘模块1‘:‘局部状态1‘, ‘模块2‘:‘局部状态2‘ }, mutations:[‘局部变化1‘,‘局部变化2‘], actions:[‘局部动作1‘,‘局部动作2‘] }
一 项目结构
二 main.js
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store/index"; Vue.config.productionTip = false; new Vue({ router, store, render: h => h(App) }).$mount("#app");
三 index.js
import Vue from "vue"; import Vuex from "vuex"; import cat from "./modules/cat"; import dog from "./modules/dog"; Vue.use(Vuex); export default new Vuex.Store({ modules: { cat, dog } });
四 cat.js
export default { // 局部状态 state: { name: "蓝白英短", age: 1 }, // 局部变化 mutations: { increment(state, payload) { state.age += payload.num; } }, // 局部动作 actions: { grow(state, payload) { setTimeout(() => { state.commit("increment", payload); }, 1000); } } };
五 dog.js
export default { // 局部状态 state: { name: "拉布拉多", age: 1 }, // 局部变化 mutations: { increment(state, payload) { state.age += payload.num; } }, // 局部动作 actions: { grow(state, payload) { setTimeout(() => { state.commit("increment", payload); }, 1000); } } };
六 HelloWorld.vue
<template> <div class="hello"> <h3>Vuex状态树</h3> <div>{{this.$store.state}}</div> <h3>各模块的局部状态</h3> <div>{{cat}} 、 {{dog}}</div> <button @click="increment({num:1})">变化</button> <button @click="grow({num:1})">动作</button> </div> </template> <script> import { mapState, mapMutations, mapActions } from "vuex"; export default { name: "HelloWorld", computed: { ...mapState(["cat", "dog"]) }, methods: { ...mapMutations(["increment"]), ...mapActions(["grow"]) } }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped lang="scss"> </style>
七 运行效果
原文:https://www.cnblogs.com/sea-breeze/p/11320484.html