关于vue.js:vuex命名空间

33次阅读

共计 2177 个字符,预计需要花费 6 分钟才能阅读完成。

mapState、mapGetters、mapMutations、mapActions 第一个参数是字符串(命名空间名称),第二个参数是数组(不须要重命名)/ 对象(须要重命名)。

mapXXXs('命名空间名称',['属性名 1','属性名 2'])

mapXXXs('命名空间名称',{

  '组件中的新名称 1':'Vuex 中的原名称 1',

  '组件中的新名称 2':'Vuex 中的原名称 2',

})

我的项目构造

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>

运行成果

正文完
 0