Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nuxt vue router afterEach guard

How can I set an afterEach handler that executes after route changes in nuxt? The middleware can be used as an beforeEach, but I could not find a way to implement the afterEach hook.

like image 847
Chris Avatar asked Jan 15 '18 15:01

Chris


People also ask

How do I protect a route in Nuxt?

You can protect routes and make them accessible only for authenticated users for example. Create middleware directory in Nuxt root folder, and create a new file called auth. js therein. Now, Nuxt will redirect user to /login page if not already authenticated (i.e., isLoggedIn is false ).

Can I use Vue router in Nuxt?

Nuxt automatically generates the vue-router configuration for you, based on your provided Vue files inside the pages directory. That means you never have to write a router config again!

What is beforeEach in Vuejs?

It looks like this beforeEach is being defined inside an initialized component, which means the first routing has already occured. Define it in the router module with your routes instead: const router = new VueRouter({ ... }) router. beforeEach((to, from, next)=>{ if ( to. name !== 'login' && !


Video Answer


1 Answers

You can create a plugin like the following:

// plugins/after-each.js:
export default async ({ app }) => {

  app.router.afterEach((to, from) => {
    // Do something
  });

}

And then reference it in nuxt.config.js:

plugins: [ { src: '~/plugins/after-each.js', mode: 'client' } ]

Note: Since Nuxt.js 2.4, mode has been introduced as option of plugins to specify plugin type, possible value are: client or server. ssr: false will be adapted to mode: 'client' and deprecated in next major release.

like image 168
Gomah Avatar answered Oct 18 '22 18:10

Gomah