vuex名稱空間

HappyCodingTop發表於2021-09-25

mapState、mapGetters、mapMutations、mapActions第一個引數是字串(名稱空間名稱),第二個引數是陣列(不需要重新命名)/物件(需要重新命名)。

mapXXXs('名稱空間名稱',['屬性名1','屬性名2'])

mapXXXs('名稱空間名稱',{

  '元件中的新名稱1':'Vuex中的原名稱1',

  '元件中的新名稱2':'Vuex中的原名稱2',

})

專案結構

image.png

mian.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 {
  namespaced: true,
  // 區域性狀態
  state: {
    name: "藍白英短",
    age: 1
  },
  // 區域性讀取
  getters: {
    desc: 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 {
  namespaced: true,
  // 區域性狀態
  state: {
    name: "拉布拉多",
    age: 1
  },
  // 區域性讀取
  getters: {
    desc: state => "寵物:" + state.name
  },
  // 區域性變化
  mutations: {
    increment(state, payload) {
      state.age += payload.num;
    }
  },
  // 區域性動作
  actions: {
    grow(context, payload) {
      setTimeout(() => {
        context.commit("increment", payload);
      }, 1000);
    }
  }
};

hello.vue

<template>
  <div class="hello">
    <h3>Vuex狀態樹</h3>
    <div>{{this.$store.state}}</div>
    <h3>mapState</h3>
    <div>{{catName}} {{catAge}}</div>
    <div>{{dogName}} {{dogAge}}</div>
    <h3>mapGetters</h3>
    <div>{{catDesc}}</div>
    <div>{{dogDesc}}</div>
    <h3>mapMutations</h3>
    <button @click="catIncrement({num:1})">貓變化</button>
    <button @click="dogIncrement({num:1})">狗變化</button>
    <h3>mapActions</h3>
    <button @click="catGrow({num:1})">貓動作</button>
    <button @click="dogGrow({num:1})">狗動作</button>
  </div>
</template>

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

export default {
  name: "HelloWorld",
  computed: {
    ...mapState("cat", {
      catName: "name",
      catAge: "age"
    }),
    ...mapState("dog", {
      dogName: "name",
      dogAge: "age"
    }),
    ...mapGetters("cat", {
      catDesc: "desc"
    }),
    ...mapGetters("dog", {
      dogDesc: "desc"
    })
  },
  methods: {
    ...mapMutations("cat", { catIncrement: "increment" }),
    ...mapMutations("dog", { dogIncrement: "increment" }),
    ...mapActions("cat", { catGrow: "grow" }),
    ...mapActions("dog", { dogGrow: "grow" })
  }
};
</script>

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

執行效果

image.png

相關文章