如何在 Nuxt.js 中设置 beforeResolve 导航防护

2024-04-27

有没有办法在 nuxt.config.js 中添加 beforeResolve 导航防护?

我的 nuxt.config.js

module.exports {
    ...
    router: {
        beforeResolve(to, from, next) {
            if (this.$store.getters.isLoggedIn)
                 next('/resource')
        }
    }
    ...
}

但它永远不会被调用!

我一直在尝试根据 vuex 存储上的用户登录状态安装组件之前实现重定向。


为此,您有两种选择。您可以通过中间件或在相应页面中设置全局规则。

// middleware/route-guard.js
export default function ({ app }) {

    app.router.beforeResolve((to, from, next) => {
        if (app.store.getters.isLoggedIn) {
            next('/resource')
        } else {
            next();
        }
    });

}

// Nuxt Page Component
export default {
    beforeResolve (to, from, next) {
        if (this.$store.getters.isLoggedIn) {
            next('/resource')
        } else {
            next();
        }
    }
  }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Nuxt.js 中设置 beforeResolve 导航防护 的相关文章

随机推荐