Vuex模块:不开启命名空间

 

模块不开启命名空间时,会共享全局命名空间。

 

 

{
  state: {
    模块1: "局部状态1",
    模块2: "局部状态2"
  },
  getters: {
    getter1() {},
    getter2() {}
  },

  mutations: ["局部变化1", "局部变化2"],
  actions: ["局部动作1", "局部动作2"]
}

 

mapState、mapGetters、mapMutations、mapActions参数是数组。

 

mapXXXs(['属性名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
  },
  // 局部读取
  getters: {
    catDesc:  state => "宠物:" + state.name
  },
  // 局部变化
  mutations: {
    increment(state, payload) {
      state.age += payload.num;
    }
  },
  // 局部动作
  actions: {
    grow(context, payload) {
      setTimeout(() => {
        context.commit("increment", payload);
      }, 1000);
    }
  }
};

 

五 dog.js

 

 

export default {
  // 局部状态
  state: {
    name: "拉布拉多",
    age: 1
  },
  // 局部读取
  getters: {
    dogDesc: state => "宠物:" + state.name
  },
  // 局部变化
  mutations: {
    increment(state, payload) {
      state.age += payload.num;
    }
  },
  // 局部动作
  actions: {
    grow(context, payload) {
      setTimeout(() => {
        context.commit("increment", payload);
      }, 1000);
    }
  }
};

 

六 HelloWorld.vue

 

<template>
  <div class="hello">
    <h3>Vuex状态树</h3>
    <div>{{this.$store.state}}</div>
    <h3>mapState</h3>
    <div>{{cat}}</div>
    <div>{{dog}}</div>
    <h3>mapGetters</h3>
    <div>{{catDesc}}</div>
    <div>{{dogDesc}}</div>
    <h3>mapMutations</h3>
    <!-- 猫狗的年龄都变化 -->
    <button @click="increment({num:1})">变化</button>
    <h3>mapActions</h3>
    <!-- 猫狗的年龄都变化 -->
    <button @click="grow({num:1})">动作</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";

export default {
  name: "HelloWorld",
  computed: {
    ...mapState(["cat", "dog"]),
    ...mapGetters(["catDesc", "dogDesc"])
  },
  methods: {
    ...mapMutations(["increment"]),
    ...mapActions(["grow"])
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
</style>

 

七 运行效果

 

 

posted on 2019-08-08 12:50  沙滩海风  阅读(739)  评论(0编辑  收藏  举报

导航