9

我尝试使用 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 操作以某种方式丢失了上下文(?),但我不知道如何处理!感谢您的每一个帮助!

4

2 回答 2

12

这就是我开始工作的方式:)

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)
  })
}
于 2016-08-27T18:52:45.717 回答
3

当您console.log('this', this)进入 store 模块时,您可以看到在该上下文中列出的调度。所以你可以像这样使用它。:

// 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);
  }
}
于 2020-04-16T18:44:43.377 回答