How to set beforeResolve navigation guard in Nuxt.js

痴心易碎 提交于 2021-01-22 12:09:06

问题


Is there a way to add beforeResolve navigation guard in nuxt.config.js?

My nuxt.config.js

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

But its never gets called!

I've been trying to achieve a redirection before the component is mounted based on the users logged in state on the vuex store.


回答1:


You have 2 options for this. You can set a global rule via the middleware or in the respective page.

// 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();
        }
    }
  }


来源:https://stackoverflow.com/questions/53322525/how-to-set-beforeresolve-navigation-guard-in-nuxt-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!