当我使用用户登录时,它会按预期将我重定向到仪表板。一旦我注销并尝试再次登录(即使使用另一个用户,并且不刷新页面),它就会在控制台中返回此错误:
如果经过身份验证,我只想在仪表板中重定向用户,即使页面未刷新,因为我确实注意到,如果刷新页面,我可以毫无问题地登录。
如果可以的话请帮助我。下面是一些代码:
登录方式
methods: {
...mapActions({
attempt: "auth/attempt",
}),
submit(credentials) {
axios
.post("http://127.0.0.1:8000/api/login", credentials)
.then((res) => {
// console.log(res.data);
if (res.data.success) {
this.attempt(res.data.token)
}
if (res.data.errors) {
this.loginErrors = res.data.errors;
} else {
this.$router.push({ name: 'dashboard' })
}
})
.catch((err) => {
if (
err.name !== "NavigationDuplicated" &&
!err.message.includes(
"Avoided redundant navigation to current location"
)
) {
console.log(err);
}
});
},
},
路由器中的仪表板路径
{
path: '/dashboard',
name: 'dashboard',
component: DashboardComponent,
beforeEnter: (to, from, next) => {
if (!store.getters['auth/authenticated']) {
return next({
name: 'home'
})
}
next()
}
},
尝试在 vuex 存储中执行操作
async attempt({ commit, state }, token) {
if (token) {
commit('SET_TOKEN', token)
}
// se non c'è
if(!state.token) {
return
}
try {
await axios.get('http://127.0.0.1:8000/api/user')
.then(res => {
commit('SET_USER', res.data)
})
} catch (e) {
commit('SET_TOKEN', null)
commit('SET_USER', null)
}
},
其他来自 vuex
namespaced: true,
state: {
token: null,
form: null,
},
getters: {
authenticated(state) {
return state.token && state.form
},
user(state) {
return state.form
},
},
mutations: {
SET_TOKEN(state, token) {
state.token = token
},
SET_USER(state, data) {
state.form = data
},
}, Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
更新:应该等待对
attempt()的调用,否则this.$router.push({ name: 'dashboard' })(因此/dashboard路由上的守卫函数)将被调用在对/api/userAPI 的调用完成之前:submit(credentials) { axios .post("http://127.0.0.1:8000/api/login", credentials) .then(async (res) => { // console.log(res.data); if (res.data.success) { await this.attempt(res.data.token) } if (res.data.errors) { this.loginErrors = res.data.errors; } else { this.$router.push({ name: 'dashboard' }) } }) .catch((err) => { if ( err.name !== "NavigationDuplicated" && !err.message.includes( "Avoided redundant navigation to current location" ) ) { console.log(err); } }); },next是一个应该准确调用的函数一次(不返回)。尝试将路由器中的代码更改为:
{ path: '/dashboard', name: 'dashboard', component: DashboardComponent, beforeEnter: (to, from, next) => { if (!store.getters['auth/authenticated']) { next({ name: 'home' }) } else { next() } } },