[英]How to call action inside action in Vuex
I try to build a really small Vue App with a Rails API.我尝试使用 Rails API 构建一个非常小的 Vue 应用程序。 So at the moment I work with Vue, Vue-Resource and Vuex.所以目前我使用 Vue、Vue-Resource 和 Vuex。 I'll fetch all users from the database und now i try to update one of them.我将从数据库中获取所有用户,现在我尝试更新其中之一。 So everythings works fine (patch User), but after running the updateUser action I want to run the fetchUsers action again to update the Vuex store.所以一切正常(补丁用户),但在运行 updateUser 操作后,我想再次运行 fetchUsers 操作以更新 Vuex 存储。
But when the fetchUsers runs inside the updateUser promise I get the following error:但是当 fetchUsers 在 updateUser 承诺内运行时,我收到以下错误:
undefined:1 Uncaught (in promise) TypeError: Cannot read property 'dispatch' of undefined
this is what my vuex/actions.js are looking:这就是我的 vuex/actions.js 正在寻找的:
export const fetchUsers = function ({ dispatch, state }) {
this.$http.get('http://localhost:3000/api/v1/users').then((response) => {
dispatch('SET_USERS', response.data)
}, (response) => {
dispatch('SET_USERS', [])
console.log(response)
})
}
export const updateUser = function ({ dispatch, state }, user) {
this.$http.patch('http://localhost:3000/api/v1/users/' + user.id, {user: user}).then((response) => {
fetchUsers()
}, (response) => {
console.log(response)
})
}
I now that the fetchUsers action somehow loses context(?) but I don't know how to deal with that!我现在 fetchUsers 操作不知何故丢失了上下文(?),但我不知道如何处理! thanks for every help!感谢每一个帮助!
this is how i got it to working :)这就是我让它工作的方式:)
import Vue from 'vue'
export const fetchUsers = ({ dispatch, state }) => {
Vue.http.get('http://localhost:3000/api/v1/users').then((response) => {
dispatch('SET_USERS', response.data)
}, (response) => {
dispatch('SET_USERS', [])
console.log(response)
})
}
export const updateUser = ({ dispatch, state }, user) => {
Vue.http.patch('http://localhost:3000/api/v1/users/' + user.id, {user: user}).then((response) => {
fetchUsers({dispatch})
}, (response) => {
dispatch('SET_USERS', [])
console.log(response)
})
}
When you console.log('this', this)
inside of store module, you can see dispatch listed in that context.当您在 store 模块中使用console.log('this', this)
,您可以看到在该上下文中列出的 dispatch。 so you can use it like so.:所以你可以像这样使用它。:
// inside of store/test.js module
export const state = () => ({
test: 'somestate'
})
export const mutations = {
ACTION_TWO(state, data) {
state.test = data;
}
}
export const actions = {
actionOne({ commit }, value) {
this.dispatch('test/actionTwo', value); // moduleName/action
},
actionTwo({ commit }, valueToCommit) {
commit('ACTION_TWO', valueToCommit);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.