首页 > 解决方案 > 在 Vuex 操作中直接操作状态与使用 'commit' 和 'getters'

问题描述

我知道直接从商店外部(例如从组件)操作 Vuex 状态通常是不好的做法;但我正在努力了解从动作中读取/更改状态的最佳实践。

我知道动作本身就有一个context对象作为参数,您可以从中获取stategetterscommit、 和dispatch属性。但我对使用这些的最佳实践感到困惑。例如:

      testAction: ({commit, getters, state}) => {

        if(state.foo === 'bar'){ // is this bad practice? 
            // ...do a thing
        }
        if(getters.getFoo === 'bar'){ // should I always read the state with a getter like this instead?
            // ...do a thing
        }

        commit('setFoo', 'foobar'); // do I always need to set the state via commit like this

        state.foo = 'foobar' // or is it fine to just do this?

      }

请看评论。在动作中操纵状态的“正确”方法是什么?我总是需要使用commitandgetters吗?如果是这样,为什么context对象甚至会暴露状态?你什么时候会在动作中使用它?谢谢。

标签: vue.jsvuex

解决方案


通过查看文档,突变操作定义如下:

动作 动作类似于突变,不同之处在于:动作不是改变状态,而是提交突变。动作可以包含任意异步操作。

突变 在 Vuex 存储中实际改变状态的唯一方法是提交突变。Vuex 突变与事件非常相似:每个突变都有一个字符串类型和一个处理程序。处理函数是我们执行实际状态修改的地方,它将接收状态作为第一个参数:(...)要记住的一个重要规则是突变处理函数必须是同步的

必须使用mutation完成状态修改,否则更新将无法通过 Vue 应用程序正确分派,组件也不会相应更新。但是您不会被迫使用操作来提交突变。您可以将操作视为突变的组合,允许您处理对状态和异步方法的复杂更改。因此,如果您的操作足够简单,请使用突变,否则请使用操作。虽然,请注意,由于突变是同步的,它们可能会冻结你的前端,直到请求的动作结束,如果动作是一个沉重的动作(Akryum 的很好的解释,vuejs 核心成员在这里)。

以类似的方式,getter 是一种从存储中检索到的“格式化”数据的方式,如文档中所述:

有时我们可能需要根据存储状态计算派生状态,例如过滤项目列表并计算它们。

这意味着如果你只需要一个简单的状态键,你不需要创建一个 getter,你可以简单地从状态中检索你需要的信息。

看看你的例子:

testAction: ({commit, getters, state}, testData) => {

    if(state.foo === 'bar'){ // is this bad practice? ==> Good to go !
        // ...do a thing
    }

    if(getters.getFoo === 'bar'){ // should I always read the state with a getter like this instead?  ==> Good to go ! but it depends on the way you can retrieve data from the state (like if you need to know the number of items within a list)
        // ...do a thing
    }

    commit('setFoo', 'testData'); // do I always need to set the state via commit like this  ==> **YES** !

    state.foo = 'foobar' // or is it fine to just do this? ==> never do this

}

此外,为了更轻松地将 VueX 集成到您的组件中,该 api 公开了一组函数来访问存储属性并将它们用作计算属性或方法 :mapActionsmapMutationsmapGettersmapState


推荐阅读