VueJS路由问题



最近我决定把我的一些应用移植到Vue上,这样我就可以学习这个框架了,但是我有点被卡住了。基本上在我登录登录视图后,我应该被重路由到我的home视图,但当我登录我的app时,它停留在登录视图上,它只在我已经登录并按下登录按钮后才起作用。在商店状态明显变化,我可以清楚地看到我的导航条响应的变化。当然,在我手动进入"/"路径后,主视图可以工作,但这不是一个好的用户体验,不是吗?

我只推断出一件事的可能原因。navguards。我不知道如何找到一个解决办法,我花了太多时间思考这个问题,我可以用一只手给我指出正确的方向。下面是一些代码片段:

登录方法:

methods: {
...mapActions({
signIn: 'signIn'
}),
handleSubmit() {
const data = {
email: this.email,
password: this.password,
};
this.signIn(data).then(() => {
this.$router.push({path: '/'})
}).catch(e => {
console.log(e)
})
},

Vuex行动:

async signIn({dispatch},data) {
const res = await axios.post("auth", data);
dispatch('auth', res.data.token)
},
async auth({commit, state}, token) {

if(token) {
commit('token', token)
}
if(!state.token) {
return
}
commit('token', token)

try {
const res = await axios.get('auth')
commit('user', res.data)
} catch (e) {
commit('user', null)
commit('token', null)
}
},

相关Vuex getter:

isAuth: (state) => {
console.log({token: state.token, user: state.user})
return state.token && state.user
},

路由器/Navguard:

{ 
name: 'Home',
path: '/', 
component: Home,
beforeEnter: (to, from, next) => {
if(!store.getters['isAuth']){
next({path: '/login'})
}else {
next()
}
} 
},

尝试await-ing在signIn函数中的调度:

async signIn({dispatch},data) {
const res = await axios.post("auth", data);
await dispatch('auth', res.data.token)
}

如果您不等待调度,那么当您呼叫this.$router.push({path: '/'})时,user可能仍然是null,并且路由保护阻止您前往/

我认为这是与承诺有关的问题,行动this.$router.push({path: '/'})可以比axios.post("auth", data);更早执行,我通常通过在方法中处理来解决这个问题:

handleSubmit() {
const data = {
email: this.email,
password: this.password,
};
const res = await this.signIn(data)
if (res?.response.status === 200) { // change to the valid condition when success
this.$router.push({path: '/'})
}
},

,然后在vuex操作中,您也必须返回响应

async signIn({dispatch},data) {
const res = await axios.post("auth", data);
dispatch('auth', res.data.token)
return res;
}

也,以防问题不是渲染正确的组件,你应该检查你的<router-view ..,添加key道具,以确保它被正确地重新渲染,例如:

<router-view :key="route.path" />

最新更新