Vuex - 将多个参数传递给突变 [英] Vuex - passing multiple parameters to mutation

查看:30
本文介绍了Vuex - 将多个参数传递给突变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 vuejs 和 Laravel 的护照对用户进行身份验证.

我无法弄清楚如何通过操作将多个参数发送到 vuex 突变.

- 商店 -

I am trying to authenticate a user using vuejs and laravel's passport.

I am not able to figure out how to send multiple parameters to the vuex mutation via an action.

- store -

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

我会非常感谢任何形式的帮助!

I would be very thankful for any kind of help!

推荐答案

Mutations 需要两个参数:statepayload,其中传递存储的当前状态Vuex 本身作为第一个参数,第二个参数包含您需要传递的任何参数.

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

的最简单方法传递一些参数是为了摧毁他们:

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

然后在你的行动中你可以简单地

Then later on in your actions you can simply

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

这篇关于Vuex - 将多个参数传递给突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆