mcanvar
mcanvar

Reputation: 475

Is there any way to get current nuxt.js middleware of page?

I am curious if we can reach the current page's middleware from any component?

Upvotes: 0

Views: 1985

Answers (2)

David
David

Reputation: 105

You can access it on

$router.matched.meta.middleware

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50777

Middleware is executed prior to the component and is not initialized within the component in any way.

Update: Persisting the state of middleware in the auth store.

export const state = () => ({
  isPrivate: false,
})

export const mutations = {
  setPrivatePage(state, value) {
    state.isPrivate = value
  },
}

export const actions = {
  privatePage({ commit }) {
    commit('setPrivatePage', true)
  },

  publicPage({ commit }) {
    commit('setPrivatePage', false)
  },
}

Dispatch the action in the middleware/auth to set isPrivate:

await store.dispatch('auth/privatePage')

I added another middleware named public to set it back to false

export default async ({ store }) => {
  await store.dispatch('auth/publicPage')
}

And finally to trigger public on every route, add it to the nuxt.config.js:

  // Router
  router: {
    middleware: 'public',
  },

Upvotes: 1

Related Questions