Reputation: 475
I am curious if we can reach the current page's middleware from any component?
Upvotes: 0
Views: 1985
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