Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
29
Help us understand the problem. What is going on with this article?
@amagurix

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

More than 1 year has passed since last update.

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)
  },
}
29
Help us understand the problem. What is going on with this article?
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
amagurix
株式会社dotbind 代表取締役/CEO 兼フロントエンドエンジニア Nuxt.js, Gatsby,jsが好き React, Vue, Ruby, PHP, AWS... etc

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
29
Help us understand the problem. What is going on with this article?