trigger function after mounting any page in nuxt

Viewed 2880

Is it possible to write middleware in Nuxt to be triggered after mounting any page.

If I use the following middleware

export default function ({ app }) {
  if (!process.server) {
    app.$somePluginFunction()
  }
}

it is triggered when navigating to that page, thus before mounting it. That is not what I am looking for.

I also know you can use the mounted() hook on an individual page, which is what I want, but I don't want to write the same mounted() hook to every page in my app manually. How can I do this?

1 Answers

There is many way to trigger a function before route change:

First use in default layout

// layout/default.vue
export default {
  watch: {
    $route () {
      console.log('route changed', this.$route)
    }
  },
}

Second use before route:

https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards

router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

Third write plugin like this:

how to write global router-function in nuxt.js

And write mixin like this :

Run function AFTER route fully rendered in Nuxt.js

Related