Vue状态管理vuex中mutations的用法
-
store
// store.js import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); // 使用常量替代 Mutation 事件类型 const CONST_COMMIT_CHANGE_BUFF = "CONST_COMMIT_CHANGE_BUFF"; export default new Vuex.Store({ state: { userInof: { token: "登陆凭证", name: "鲁班七号" } // buff: "带蓝buff的" }, getters: {}, mutations: { COMMIT_CHANGE_BUFF(state, obj) { Vue.set(state, "buff", "带蓝buff的"); // 没有在state初始化 buff,则使用 Vue.set()设置 state.buff = obj.buff; }, [CONST_COMMIT_CHANGE_BUFF](state, obj) { Vue.set(state, "buff", "带蓝buff的"); state.buff = obj.buff; } }, actions: {}, modules: {} });
-
App.vue
// App.vue <template> <div id="app"> <p>{{ buff }} - {{ name }}</p> <div> <button @click="change({ buff: '带大龙buff的' })"> 使用mapMutations辅助函数(对象形式) </button> </div> <div> <button @click="COMMIT_CHANGE_BUFF({ buff: '带小龙buff的' })"> 使用mapMutations辅助函数(数组形式) </button> </div> <div> <button @click="CONST_COMMIT_CHANGE_BUFF"> 使用常量的形式提交 </button> </div> <div> <button @click="chageBuff(1)"> 使用字符串形式 </button> </div> <div> <button @click="chageBuff(2)"> 使用对象形式 </button> </div> </div> </template> <script> import { mapState, mapMutations } from "vuex"; export default { computed: { ...mapState({ name: status => status.userInof.name, buff: status => status.buff }) }, methods: { ...mapMutations({ change: "COMMIT_CHANGE_BUFF" // 将 `this.change()` 映射为 `this.$store.commit('COMMIT_CHANGE_BUFF')` }), ...mapMutations(["COMMIT_CHANGE_BUFF"]), // 将 `this.COMMIT_CHANGE_BUFF()` 映射为 `this.$store.commit('COMMIT_CHANGE_BUFF')` CONST_COMMIT_CHANGE_BUFF() { this.$store.commit("CONST_COMMIT_CHANGE_BUFF", { buff: "带红buff的" }); }, CONST_COMMIT_CHANGE_BUFF() { this.$store.commit("CONST_COMMIT_CHANGE_BUFF", { buff: "带红buff的" }); }, chageBuff(val) { if (val === 1) { this.$store.commit("COMMIT_CHANGE_BUFF", { buff: "没有buff的" }); } if (val === 2) { this.$store.commit({ type: "COMMIT_CHANGE_BUFF", buff: "有buff的" }); } } } }; </script>
vuex getters 参考:https://vuex.vuejs.org/zh/guide/mutations.html
开发工具