【问题标题】:Nuxt watch does not redirectNuxt 手表不重定向
【发布时间】: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
        );
    }
}

【问题讨论】:

    标签: vue.js nuxt.js router


    【解决方案1】:

    您是否尝试过为重定向创建一个方法并在您的手表处理程序中调用该方法?

    所以代替 this.$router.push 做 this.redirectUser()

    在方法'redirectUser()'中做:

    this.$router.push({'name': 'login'})
    

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2018-07-17
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多