Sch*_*esi 86 vue.js vuex vuejs2
我正在尝试使用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)
}
})
Run Code Online (Sandbox Code Playgroud)
- 登录方法 -
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()
})
})
}
Run Code Online (Sandbox Code Playgroud)
我会非常感谢任何帮助!
Nit*_*Nit 122
Mutations需要两个参数:state并且payload,当存储的当前状态由Vuex本身作为第一个参数传递时,第二个参数包含您需要传递的任何参数.
传递大量参数的最简单方法是破坏它们:
mutations: {
authenticate(state, { token, expiration }) {
localStorage.setItem('token', token)
localStorage.setItem('expiration', expiration)
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的行动中,你可以简单地
commit('authenticate', {
token,
expiration
})
Run Code Online (Sandbox Code Playgroud)
pet*_*ief 68
简单来说,您需要将有效负载构建为密钥数组
payload = {'key1': 'value1', 'key2': 'value2'}
Run Code Online (Sandbox Code Playgroud)
然后将有效负载直接发送到操作
`this.$store.dispatch('yourAction', payload)`
Run Code Online (Sandbox Code Playgroud)
你的行动没有变化
yourAction: ({commit}, payload) => {
commit('YOUR_MUTATION', payload )
},
Run Code Online (Sandbox Code Playgroud)
在你的变异中用键调用值
'YOUR_MUTATION' (state, payload ){
state.state1 = payload.key1
state.state2 = payload.key2
Run Code Online (Sandbox Code Playgroud)
},
Ntw*_*ste 12
我认为这可以很简单,假设您将在阅读时将多个参数传递给您的动作,那里的动作仅接受两个参数context,payload这是您要在动作中传递的数据,所以让我们举个例子
设置动作
代替
actions: {
authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
}
Run Code Online (Sandbox Code Playgroud)
做
actions: {
authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
}
Run Code Online (Sandbox Code Playgroud)
调用(调度)动作
代替
this.$store.dispatch({
type: 'authenticate',
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
Run Code Online (Sandbox Code Playgroud)
做
this.$store.dispatch('authenticate',{
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助
| 归档时间: |
|
| 查看次数: |
72787 次 |
| 最近记录: |