从行动中调用 getters

有没有一种方法可以让调度/操作在其中调用 getter?

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;
}
}

那么这里最好的练习是什么?使用变异来更改状态,然后获取状态并将其传递给操作,这些操作将执行异步函数,还是需要重新构造实现?

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

或者

完成所有操作(对操作进行变异,并且不需要 getter 就可以完成操作/异步方法) ?

88358 次浏览

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.

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').

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

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

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

You have access to getters inside an action:

getters: {
getUser(state){
return state.user
}
}


actions : {
myAction({ getters }){
let user = getters.getUser
}
}

If you are using nuxt and isolated files in vuex, like this =

store -
|
|-- index.js
|
|-- store.js
|
|-- product.js

// store.js
export const getters = {
getNameStore: state => state.getNameStore ? state.getNameStore : null
};

I want the getNameStore of the store.js into product.js

// product.js
export const actions = {
setResultSearch({ commit, dispatch }, text) {
console.log(
'getNameStore',
this.getters["store/getNameStore"]
);
};

this.getters["store/getNameStore"]

Action handlers receive a context object which exposes the same set of methods/properties on the store instance, so you can call context.commit to commit a mutation, or access the state and getters via context.state and context.getters

   actions: {
sendDataToServer(context, payload) {
// context object contains state, commit, getters
context.getters.getAppData
}
},

Refer docs: https://vuex.vuejs.org/guide/actions.html#dispatching-actions