60
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2018-02-20

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)
  },
}
60
34
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
60
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?