【发布时间】:2021-11-08 11:51:09
【问题描述】:
我有一个带有个人资料页面的 Nuxt 应用程序。这个页面有一个观察者检查 store.state.auth.isAuthenticated 值。如果是假观察者应该重定向到登录页面。奇怪的是,虽然条件被正确评估,但它并没有重定向到登录。
watch: {
'$store.state.auth.isAuthenticated': {
imediate: true,
deep: false,
handler(newVal) {
if( !newVal ) this.$router.push({'name': 'login'});
}
},
},
正如我上面写的,条件被正确评估,但它不会触发 $router.push()。我不明白。这段代码有什么问题?
编辑:它在 auth.js 中间件中创建了无限循环。
import { createNavigationGuard } from "~/plugins/navigation-guard.js";
export default function (context) {
if (process.client) {
const watchedStores = [];
const unwatchStore = (unwatch) => {
if (typeof unwatch === "function") {
unwatch();
}
};
// TODO: Find out whether the watchers persist after each route
// Unwatch previous route - this could be necessary for performance
console.log('watchedStores');
console.log(watchedStores);
unwatchStore(watchedStores.pop());
const unwatch = context.store.watch(
(state) => {
return state.auth.isAuthenticated;
},
(isAuthenticated) => {
createNavigationGuard(context, isAuthenticated);
},
{
immediate: true,
}
);
// it's not necessary to reassign unwatched variable to undefined with array
watchedStores.push(unwatch);
}
if (process.server) {
createNavigationGuard(
context,
context.store.state.auth.isAuthenticated
);
}
}
【问题讨论】: