将vuex商店的一部分作为动作的有效载荷分派是否正确?

问题描述 投票:1回答:1

我对这个vuex商店有一些疑问

export default {
    state: {
        resultSet: [
            {
                name: "result 1"
                deep: {
                    inside: {
                        isLoading: false
                    }
                }
            },
            {
                name: "result 2"
                deep: {
                    inside: {
                        isLoading: false
                    }
                }
            },
        ]
    },
    actions: {
        /*
        r is an item of the resultSet in the store (so r is a part of the store)
        */
        sendQuery(context, r) {
            //Here I mutate r directly (it means that I mutated the store directly without commit a mutation)

            r.deep.inside.isLoading = true;

            //Everything work, the UI is updated along with the state changes, but I'm not sure that 
            //I'm doing the right thing (mutate the store indirectly without committing a mutation)
        }
    }
}

问题:

  1. 将商店的一部分作为行动的有效载荷派遣是否正确? =>动作可能直接改变r的状态。
  2. 在上述行动中改变r.deep.inside.isLoading=true是正确的吗?
vue.js vuex flux
1个回答
3
投票
  1. 将商店的一部分作为行动的有效载荷派遣是否正确? =>动作可能直接改变r的状态。

状态在有效载荷中是好的。但是动作不能直接修改状态。

  1. 在上述行动中改变r.deep.inside.isLoading=true是正确的吗?

不。来自docs

行动不是改变状态,而是提交突变。

动作应该只提交突变(类似于Vuex中的“事件总线”和/或互斥)。

对于动作(类似于事件本身)而言,调度其他类似事件的事情似乎很愚蠢,但是突变事件(“提交”)具有特殊规则,例如they must be synchronous,而动作可以在提交突变之前执行异步任务。

在开发过程中充分利用strict mode,这样Vuex肯定会在您修改状态时通知您。

© www.soinside.com 2019 - 2024. All rights reserved.