如何在Vuex中调用动作内部的动作

时间:2016-08-27 18:19:38

标签: javascript ruby-on-rails vue.js vuex

我尝试使用Rails API构建一个非常小的Vue应用程序。所以目前我与Vue,Vue-Resource和Vuex合作。我将从数据库中获取所有用户,现在我尝试更新其中一个用户。所以每个事情都运行正常(补丁用户),但在运行updateUser操作后,我想再次运行fetchUsers操作来更新Vuex存储。

但是当fetchUsers在updateUser promise中运行时,我收到以下错误:

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动作以某种方式失去了上下文(?)但我不知道如何处理它!谢谢你的帮助!

2 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:0)

在商店模块中console.log('this', this)时,您会看到在该上下文中列出的调度。因此您可以像这样使用它:

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