【问题标题】:Correct way create action in vuex在 vuex 中创建动作的正确方法
【发布时间】:2018-05-18 12:52:20
【问题描述】:

创建 simple(不链接 then/catch 调用)vuex-actions as a1 就足够了吗?或者我每次都需要用 Promise 创建为 a2 (+还添加拒绝分支)?

提前谢谢你...

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

const debug = process.env.NODE_ENV !== 'production';

export default new Vuex.Store({
    state: { ... }
    ...
    actions: {
        a1: (state, response) => {
            state.commit('setNavMenu',{signIn: true, signUp: true, signOut: false});
        ...        
        },
        a2: (state, response) => {
            return new Promise((resolve) => {
                state.commit('setNavMenu',{signIn: true, signUp: true, signOut: false});
            ...
            resolve();
            });
        },        

...
     

【问题讨论】:

标签: javascript vue.js vuex


【解决方案1】:

可以创建一个同步操作(无需承诺或其他异步代码),就像您的第一个操作a1

但是,您可以直接调用突变函数,在a1 的情况下,它将是setNavMenu。 动作和突变之间的主要区别在于,当突变不能时,动作可以是异步的,基本上如果你不需要你的动作来执行异步。代码,您不需要执行任何操作,只需执行突变即可。

更多细节可以查看官方文档https://vuex.vuejs.org/en/actions.html

【讨论】:

    【解决方案2】:

    您不这样做,只有当操作具有异步方面或想要从您的操作中获得响应时,您才会这样做。

    如果您的所有更新都是同步性质的(不依赖 API 或任何异步反馈),您甚至可以直接调用变更,完全跳过操作。

    即(来自官方文档)

    import { mapMutations } from 'vuex'
    
    export default {
      // ...
      methods: {
        ...mapMutations([
          'increment', // map `this.increment()` to `this.$store.commit('increment')`
    
          // `mapMutations` also supports payloads:
          'incrementBy' // map `this.incrementBy(amount)` to `this.$store.commit('incrementBy', amount)`
        ]),
        ...mapMutations({
          add: 'increment' // map `this.add()` to `this.$store.commit('increment')`
        })
      }
    }
    

    使用操作的原因是当您处理异步更改时,例如当您希望您的突变使用来自 API 的数据时。

    【讨论】:

      猜你喜欢
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 2019-07-31
      • 2012-06-18
      • 2016-06-06
      • 2021-03-02
      • 1970-01-01
      相关资源
      最近更新 更多