我正在用vuejs和laravel的护照验证一个用户的身份。我无法弄清楚如何通过一个操作将多个参数发送到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()
})
})
}
我将非常感谢任何形式的帮助!
突变需要两个参数:state和payload,其中存储的当前状态由Vuex本身作为第一个参数传递,第二个参数保存需要传递的任何参数。
传递一些参数最简单的方法是销毁它们:
mutations: {
authenticate(state, { token, expiration }) {
localStorage.setItem('token', token);
localStorage.setItem('expiration', expiration);
}
}
然后在你的行动中,你可以简单地
store.commit('authenticate', {
token,
expiration,
});
简单来说,您需要将有效载荷构建到一个键数组中
payload = {'key1': 'value1', 'key2': 'value2'}
然后将有效载荷直接发送到动作
this.$store.dispatch('yourAction', payload)
你的行动没有变化
yourAction: ({commit}, payload) => {
commit('YOUR_MUTATION', payload )
},
在您的突变中,使用键调用值
'YOUR_MUTATION' (state, payload ){
state.state1 = payload.key1
state.state2 = payload.key2
},
我认为这很简单
假设你要传递多个参数给action当你读到那里action只接受两个参数context和payload这是你想在action中传递的数据让我们举个例子
设置动作
而不是
actions: {
authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
}
do
actions: {
authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
}
呼叫(调度)开始
而不是
this.$store.dispatch({
type: 'authenticate',
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
do
this.$store.dispatch('authenticate',{
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
希望这能有所帮助