[英]How to call action inside action in Vuex
我嘗試使用 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 操作不知何故丟失了上下文(?),但我不知道如何處理! 感謝每一個幫助!
這就是我讓它工作的方式:)
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)
})
}
當您在 store 模塊中使用console.log('this', this)
,您可以看到在該上下文中列出的 dispatch。 所以你可以像這樣使用它。:
// 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.