vuex的使用 1.组件中通过dispatch事件触发actions eg: methods: { 事件名: function() { this.$store.dispatch("键值名", 需要存储的值); }, } 2.通过actions进行commit提交给mutation eg:action.js 键值名({commit},需要存储的值){ commit(types.NEWSHOW,需要存储的值); }, 3.mutation通过mutate给state eg:mutation.js [types.NEWSHOW](state,需要存储的值){ state.需要存储的值的名称=需要存储的值; }, 4.在store.js里进行getter处理 eg: show(state){ return state.需要存储的值的名称 }, 5.在组件里进行获取 eg: import { mapGetters } from "vuex"; computed: { ...mapGetters(["show"]) }, 6.注意:使用常量替代 Mutation 事件类型 eg:mutation_type.js export const NEWSHOW="NEWSHOW" eg:目录结构: store action.js import * as types from './mutation_type'这是全局引入,也可以按需引入 export default{ newShow({commit},bData){ commit(types.NEWSHOW,bData); } } mutation.js import * as types from './mutation_type' export default{ [types.NEWSHOW](state,bData){ state.show=bData; } } mutation_type.js export const NEWSHOW="NEWSHOW" store.js import Vue from 'vue' import Vuex from 'vuex' import actions from './action' import mutations from './mutation' Vue.use(Vuex) const store = new Vuex.Store({ state:{ show: false, }, actions, mutations, getters:{ show(state){ console.log(state.show) return state.show } }) export default store
vuex封装
最新推荐文章于 2024-06-01 10:00:35 发布