Vuex-Actions、Mutations、模块化

本文详细介绍了 Vuex 中 Mutation 和 Action 的概念与使用方法。Mutation 是改变 Vuex store 状态的唯一途径,同步进行,而 Action 可包含异步操作并提交 Mutation。文中通过示例展示了如何定义、调用 Mutation 和 Action,以及如何在组件中映射和分发它们。此外,还提到了处理复杂异步流程的策略,如 Promise 和 async/await 的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

核心概念-Mutations

1. 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。

  • 包含多个直接更新 state 的方法(回调函数)的对象
  • 被动触发:action 中的 commit('mutation 名称')
  • 每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)
  • 这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
  • 只能包含同步的代码, 不能写异步代码

2. 方法定义与调用

//定义
const mutations = {
    increment (state) {
      // 变更状态
      state.count++
    }
}

//调用触发,一般在action中
store.commit('increment')

3. 向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)

const mutations  = {
  increment (state, n) {
    state.count += n
  }
}

store.commit('increment', 10)

4. 当需要在对象上添加新属性时,两种方法

  1. 使用 Vue.set(obj, 'newProp', 123)
  2. 以新对象替换老对象。例如,利用对象展开运算符
state.obj = { ...state.obj, newProp: 123 }

5. 组件中提交mutation

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    //数组形式
    ...mapMutations([
      // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
      'increment', 

      // `mapMutations` 也支持载荷:
      // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
      'incrementBy' 
    ]),
    //对象形式,方便取别名
    ...mapMutations({
      // 将 `this.add()` 映射为 `this.$store.commit('increment')`
      add: 'increment' 
    })
  }
}

6. 使用常量定义mutations

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'

// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'

const store = new Vuex.Store({
  state: { ... },
  mutations: {
    // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})

核心概念-Actions

1. Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

2. 定义与调用

//定义
const actions = {
    increment (context) {
      context.commit('increment')
    }
}

//调用,一般在组件methods中
this.$store.dispatch('increment')

3. context 对象

  • 调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters
  • context 对象不是 store 实例本身

4. 组件中分发actions

import { mapActions } from 'vuex'

export default {

  methods: {
    //数组形式
    ...mapActions([
      // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
      'increment', 

      // `mapActions` 也支持载荷
      //将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
      'incrementBy' 
    ]),

    //对象形式
    ...mapActions({
      // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
      add: 'increment' 
    })
  }
}

5. 异步处理的action

  • 如何才能组合多个 action,以处理更加复杂的异步流程?
  • store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise
//使用Promise函数
actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  },

  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

//使用async / await
actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

store.dispatch('actionA').then(() => {
  // ...
})

核心概念-Modules

  • 目的‌:将大型应用的状态分割成多个模块,避免单一状态树过于臃肿‌
  • 每个模块有自己的state、mutations、actions等
  • 定义子模块
// moduleA.js
const moduleA = {
  namespaced: true, // 开启命名空间‌
  state: () => ({ 
    count: 10,
    list: ['苹果', '香蕉']
  }),
  mutations: {
    increment(state, num) {
      state.count += num;
    }
  },
  actions: {
    asyncIncrement(context, num) {
      setTimeout(() => {
        context.commit('increment', num);
      }, 1000);
    }
  }
};

// moduleB.js
const moduleB = {
  state: () => ({ 
    user: 'admin' 
  }),
  getters: {
    formatUser: (state) => state.user.toUpperCase()
  }
};
  • 将子模块整合到主模块的 modules 选项中
// store.js
import { createStore } from 'vuex';
import moduleA from './moduleA';
import moduleB from './moduleB';

const store = createStore({
  modules: {
    a: moduleA, // 模块名称为 'a'‌
    b: moduleB
  }
});
  • 访问模块的 state,通过$store.state.模块名‌
// 组件中
console.log(this.$store.state.a.count); // 输出 10‌  
console.log(this.$store.state.b.user);  // 输出 'admin'
  • 调用模块的 mutations 和 actions
// 触发 moduleA 的 increment mutation
this.$store.commit('a/increment', 5); // state.a.count 变为 15‌ 
// 触发 moduleA 的异步 action
this.$store.dispatch('a/asyncIncrement', 3); // 延迟 1 秒后 state.a.count 变为 18‌ 
  • 使用模块的 getters‌,通过 $store.getters['模块名/属性名']
console.log(this.$store.getters['b/formatUser']); // 输出 'ADMIN'‌ 
  • 辅助函数映射模块属性

import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState('a', ['count', 'list']), // 映射 moduleA 的 state‌ 
    ...mapGetters('b', ['formatUser'])  // 映射 moduleB 的 getters‌ 
  },
  methods: {
    ...mapMutations('a', ['increment']), // 映射为 this.increment(5)
    ...mapActions('a', ['asyncIncrement'])
  }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值