我尝试使用 Rails API 构建一个非常小的 Vue 应用程序。所以目前我使用 Vue、Vue-Resource 和 Vuex。我将从数据库中获取所有用户,现在我尝试更新其中一个。所以一切工作正常(补丁用户),但在运行 updateUser 操作后,我想再次运行 fetchUsers 操作以更新 Vuex 存储。
但是当 fetchUsers 在 updateUser 承诺内运行时,我收到以下错误:
undefined:1 Uncaught (in promise) TypeError: Cannot read property 'dispatch' of undefined
这就是我的 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)
})
}
我现在 fetchUsers 操作以某种方式丢失了上下文(?),但我不知道如何处理!感谢您的每一个帮助!