我有一个代码片段,工作正常。header.vue
onLogout(){
this.logout({ router: this.$router });
}
存储.js(操作(
logout({commit}, {router}){
commit('clearAuthData')
router.replace('/')
}
这样做的作用是注销功能清除idToken并将用户重定向到欢迎屏幕。这工作正常。但是在同一个 header.vue 组件中,我无法通过路由器并在商店内读取它.js。它说路由器未定义。为什么会发生这种情况,我该如何解决这个问题?这是我的代码。header.vue
onLogin () {
const formData = {
email: this.email,
password: this.password,
returnSecureToken:true
}
this.$store.dispatch('login',{
email: formData.email,
password: formData.password
},{ router: this.$router })
console.log(formData)
}
存储.js(操作(
login({commit},{router},authData){
axios.post('http://localhost/laravel_back/public/api/login',authData
)
.then(res => {
console.log("Backend response",res)
commit('authUser',{
token:res.data[0].token,
userName:res.data[1][0].fname,
id:res.data[2][0].id,
type:res.data.type
})})
.catch(error => console.log(error))
router.replace('/student')
}
为什么这不起作用,除了每次传递之外.js是否有更有效的方法将路由器传递到商店。
更好的方法(对我来说(只是导入路由器对象,例如:
路由器.js
const router = new Router({
mode: 'history',
routes
})
export default router
操作.js
import router from '../my/path/to/router'
//whithin an action
router.push('/foo')
我认为 VueX 操作只能接受一个参数。因此,您必须在这些参数中包含路由器:
this.$store.dispatch('login',{
email: formData.email,
password: formData.password,
router: this.$router
})
login({commit}, options){
return axios.post('http://localhost/laravel_back/public/api/login',{email: options.email, password: options.password}).then(res => {
console.log("Backend response",res)
commit('authUser', {
token:res.data[0].token,
userName:res.data[1][0].fname,
id:res.data[2][0].id,
type:res.data.type
})
options.router.replace('/student')
}).catch(error => console.log(error))
}
但最好使用@DobleL答案。一个问题已经有同样的问题:如何从 Vuex 操作中使用 vue 路由器导航
这样,您就不必每次要进行重定向时都通过路由器。