31
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Vuexでのaction, mutationの引数指定での注意点

Vuexで削除(destroy)のActionを定義し、こんな感じで実行した場合

// 正しくない呼び出し方
this.$store.dispatch('destroy', id, index)

actionメソッドの第2引数までしか使用できず、第3引数はundefinedになってしまいます。

※この部分: destroy ({ commit, state }, id, index) {

const actions = {
  // 引数定義が正しくない
  destroy ({ commit, state }, id, index) {
    return new Promise((resolve, reject) => {
      Bank.delete(id, data => {
        if ( data.error === null ) {
          commit(types.REMOVE_BANK, index)
          resolve(data)
        } else {
          commit(types.REQUEST_ERROR, data.error)
          reject(data.error)
        }
      }).catch((error) => {
        commit(types.REQUEST_ERROR, error)
        reject(error)
      })
    })
  },
},

const mutations = {
  [types.RECEIVE_BANKS] (state, banks) {
    state.banks = banks
  },
  [types.REMOVE_BANK] (state, index) {
    state.banks.splice(index, 1)
  },
}

以下のように修正する

this.$store.dispatch('destroy', {id: id, index: index})
const actions = {
  destroy ({ commit, state }, { id, index }) {
    return new Promise((resolve, reject) => {
      Bank.delete(id, data => {
        if ( data.error === null ) {
          commit(types.REMOVE_BANK, index)
          resolve(data)
        } else {
          commit(types.REQUEST_ERROR, data.error)
          reject(data.error)
        }
      }).catch((error) => {
        commit(types.REQUEST_ERROR, error)
        reject(error)
      })
    })
  },
}
const mutations = {
  [types.RECEIVE_BANKS] (state, banks) {
    state.banks = banks
  },
  [types.REMOVE_BANK] (state, index) {
    state.banks.splice(index, 1)
  },
}

mutationも同様です。

const actions = {
  destroy ({ commit, state }, { id, index }) {
    commit(types.REMOVE_BANK, {id: id, index: index})
  }
}
const mutations = {
  [types.REMOVE_BANK] (state, { id, index }) {
    state.banks.splice(index, 1)
  },
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
31
Help us understand the problem. What are the problem?