source

Vuex에서 내부 작업을 호출하는 방법

goodcode 2022. 8. 1. 22:43
반응형

Vuex에서 내부 작업을 호출하는 방법

Rails API를 사용하여 매우 작은 Vue App을 구축하려고 합니다.현재는 Vue, Vue-Resource 및 Vuex를 사용하고 있습니다.데이터베이스에서 모든 사용자를 가져오고 그 중 하나를 업데이트하려고 합니다.따라서 모든 것이 정상적으로 동작하지만(사용자 패치 적용), updateUser 액션을 실행한 후 fetchUsers 액션을 다시 실행하여 Vuex 스토어를 업데이트합니다.

단, updateUser에서 fetchUsers가 실행되면 다음 오류가 나타납니다.

undefined:1 Uncaught (in promise) TypeError: Cannot read property 'dispatch' of undefined

my vuex/actions.displays는 다음과 같습니다.

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

언제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);
  }
}

언급URL : https://stackoverflow.com/questions/39184335/how-to-call-action-inside-action-in-vuex

반응형