1. ホーム
  2. vue.js

[解決済み】Vuex - ミューテーションに複数のパラメータを渡す

2022-04-15 21:31:27

質問

vuejsとlaravelのpassportを使ってユーザー認証をしようとしています。

アクションで複数のパラメータをvuexのミューテーションに送信する方法がわかりません。

- ストア

export default new Vuex.Store({
  state: {
    isAuth: !!localStorage.getItem('token')
  },
  getters: {
    isLoggedIn(state) {
      return state.isAuth
    }
  },
  mutations: {
    authenticate(token, expiration) {
      localStorage.setItem('token', token)
      localStorage.setItem('expiration', expiration)
    }
  },
  actions: {
    authenticate: ({
      commit
    }, token, expiration) => commit('authenticate', token, expiration)
  }
})

- ログイン方法

login() {
  var data = {
    client_id: 2,
    client_secret: '**************************',
    grant_type: 'password',
    username: this.email,
    password: this.password
  }
  // send data
  this.$http.post('oauth/token', data)
    .then(response => {
      // send the parameters to the action
      this.$store.dispatch({
        type: 'authenticate',
        token: response.body.access_token,
        expiration: response.body.expires_in + Date.now()
      })
    })
}

どんなことでもいいので、よろしくお願いします

どのように解決するのですか?

変異は2つの引数を必要とします。 statepayload ここで、ストアの現在の状態はVuex自身によって第1引数として渡され、第2引数には渡す必要のあるパラメータが格納されます。

最も簡単な方法は 複数のパラメータを渡す 破棄する :

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

そして、後のアクションでは、単純に

store.commit('authenticate', {
    token,
    expiration,
});