我正在尝试使用vuejs和laravel的护照来验证用户。
我无法弄清楚如何通过通过动作。
- 商店 -
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本身作为第一个参数传递,第二个参数保留了您需要传递的任何参数。p>传递许多参数的最简单方法是破坏它们:
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
},
我认为这可以很简单假设您将在读取操作时将多个参数传递给您的操作,仅接受两个参数context
和payload
,这是您要通过操作中传递的数据,以便以示例为例
设置操作
而不是
actions: {
authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
}
做
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()
})
做
this.$store.dispatch('authenticate',{
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
希望这会有所帮助