Javascript Vuex:从动作中调用 getter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52048944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:55:52  来源:igfitidea点击:

Vuex: Call getters from action

javascriptecmascript-6vuejs2vuex

提问by The Bassman

Is there a way for a dispatch/action to call a getter inside of it?

有没有办法让调度/动作在其中调用吸气剂?

mutations: {
    setData(state, data) {
        state.data = data;
    }
}
actions: {
    sendDataToServer({ commit }, payload) {
        // call getter (data) and assign to variable
        // do async functions from the data returned
    }
},
getters: {
    getAppData: state => () => {
        return state.data;
    }
}

So what's the best practice here? Using the mutation to change the state and then get the state and pass it to action which will then execute the async function or do I need to restructure my implementation?

那么这里的最佳实践是什么?使用突变来改变状态,然后获取状态并将其传递给动作,然后执行异步函数还是我需要重构我的实现?

call mutation -> get the data via getter -> call action

调用变异 -> 通过 getter 获取数据 -> 调用动作

OR

或者

do it all on the action (do mutation on the action and do the action/async method without the need of the getter)?

在动作上做这一切(在动作上做变异并在不需要 getter 的情况下执行动作/异步方法)?

回答by Tugay ?lik

In addition to commit, actions has default injected parameters which are dispatch, gettersand rootGetters. So you can simply write;

除了提交之外,操作还具有默认注入参数,即dispatch,gettersrootGetters。所以你可以简单地写;

sendDataToServer({ commit, getters }, payload)to access getters.

sendDataToServer({ commit, getters }, payload)访问吸气剂。

回答by Sujil Maharjan

In the action, you see the first parameter has {commit}in it. Similarly, you can pass {commit, state}. This way, you can directly access the state.data.

在操作中,您会看到其中包含第一个参数{commit}。同样,您可以通过{commit, state}. 这样,您就可以直接访问 state.data。

I think in your example, you would want to do the action because you can call the mutation from inside action itself using commit('setData').

我认为在您的示例中,您会想要执行该操作,因为您可以使用commit('setData').

The first parameter is there for you to use state and mutation as you prefer. Personally, I have only worked on projects where you do the action first and do mutation to store it in the app. For example, if I want to store a car info in the server somewhere, first I would do the action (and save it to remote db). Once I confirm that it saved in db, I would locally mutate in the store. This totally depends on case by case basis. But good thing is that you can mutate from inside the action

第一个参数供您根据需要使用状态和突变。就我个人而言,我只从事过先执行操作并进行变异以将其存储在应用程序中的项目。例如,如果我想在服务器中某处存储汽车信息,首先我会执行操作(并将其保存到远程数据库)。一旦我确认它保存在 db 中,我就会在商店中进行本地变异。这完全取决于具体情况。但好处是你可以从动作内部进行变异