Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set beforeResolve navigation guard in Nuxt.js

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.

like image 577
Harish Mohan Avatar asked Nov 15 '18 15:11

Harish Mohan


1 Answers

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();
        }
    }
  }
like image 132
4ern Avatar answered Sep 27 '22 22:09

4ern