Wenn ich mich als Benutzer anmelde, werde ich wie erwartet zum Dashboard weitergeleitet. Sobald ich mich abmelde und erneut versuche, mich anzumelden (auch mit einem anderen Benutzer und ohne Aktualisierung der Seite), wird in der Konsole dieser Fehler zurückgegeben:
Ich m?chte den Benutzer im Dashboard nur dann umleiten, wenn er authentifiziert ist, auch wenn die Seite nicht aktualisiert wird, da mir aufgefallen ist, dass ich mich ohne Probleme anmelden kann, wenn ich die Seite aktualisiere.
Bitte helfen Sie mir, wenn Sie k?nnen. Hier ist ein Code:
Anmeldemethode
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); } }); }, },
Dashboard-Pfad im Router
{ path: '/dashboard', name: 'dashboard', component: DashboardComponent, beforeEnter: (to, from, next) => { if (!store.getters['auth/authenticated']) { return next({ name: 'home' }) } next() } },
Versuchen Sie, Vorg?nge im Vuex-Speicher auszuführen
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) } },
Andere von 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 }, },
更新:應(yīng)該等待對 attempt()
的調(diào)用,否則 this.$router.push({ name: 'dashboard' })
(因此 /dashboard
路由上的守衛(wèi)函數(shù))將被調(diào)用在對 /api/user
API 的調(diào)用完成之前:
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
是一個應(yīng)該準確調(diào)用的函數(shù)一次(不返回)。
嘗試將路由器中的代碼更改為:
{ path: '/dashboard', name: 'dashboard', component: DashboardComponent, beforeEnter: (to, from, next) => { if (!store.getters['auth/authenticated']) { next({ name: 'home' }) } else { next() } } },