VueX优化

it2026-10-02  7

1.#mapGetters 辅助函数 mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:

//首先导入mapGetters import { mapGetters } from 'vuex' export default { // ... computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }

如果你想将一个 getter 属性另取一个名字,使用对象形式:

...mapGetters({ // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount` doneCount: 'doneTodosCount' })

2.在组件中分发 Action 你在组件中使用 this.$store.dispatch(‘xxx’) 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

import { mapActions } from 'vuex' export default { // ... methods: { ...mapActions([ 'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')` // `mapActions` 也支持载荷: 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)` ]), ...mapActions({ add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')` }) } } state export default { isFullScreen: false } mutations export default { changeFullScreen (state, flag) { state.isFullScreen = flag } } export default new Vuex.Store({ // state:用于保存全局共享的数据 state: state, mutations: mutations, actions: actions, getters: getters /* 很多代码放在一起会导致不容易后期维护 state: { isFullScreen: false }, // mutations:用于保存修改全局共享的数据的方法 mutations: { changeFullScreen (state, flag) { state.isFullScreen = flag } }, // actions 用于保存触发mutations中保存的方法的方法 actions: { setFullScreen ({ commit }, flag) { commit('changeFullScreen', flag) } }, getters: { isFullScreen (state) { return state.isFullScreen } } */ })

4.actions里的字符串修改为常量 创建一个mutations-type

export const SET_FULL_SCREEN = 'SET_FULL_SCREEN'

mutations.js

import { SET_FULL_SCREEN } from './mutations-type' export default { /* changeFullScreen (state, flag) { state.isFullScreen = flag } */ //想让常量作为方法名称 要加[] [SET_FULL_SCREEN] (state, flag) { state.isFullScreen = flag } }

actions:

import { SET_FULL_SCREEN } from './mutations-type' export default { /* setFullScreen ({ commit }, flag) { commit('changeFullScreen', flag) } */ setFullScreen ({ commit }, flag) { commit(SET_FULL_SCREEN, flag) } }
最新回复(0)