NUXT 3: How to use routing middleware in layout? (Can I?)
P粉619896145
P粉619896145 2023-10-26 12:57:37
0
2
664

I've been looking to use Nuxt middleware in layout. But I'm not sure if it is possible, but, since I used it inNuxt 2, it might be possible inNuxt 3.

The project has 2 different layouts:Public.vueandAdmin.vue. I only want to use the middleware in pages usingManage Layout. Because the page using it can only be accessed by logged in users and the check is done inside the middleware.

I tried this (doesn't work):

Manage layout|Manage.vue

 



Middleware | adminAuth.ts

export default defineNuxtRouteMiddleware((to, from) => { console.log(to); console.log("Acessando o admin auth middleware"); })


P粉619896145
P粉619896145

reply all (2)
P粉609866533

Middleware cannot be used in layout because middleware can only be used in pages, but you can try this method.

Create global middleware by declaring the.globalsuffix after the middleware file name, such asauth.global.ts.

In theauth.global.tsfile, you can use layout metas as logic to simulate as if the middleware was in your layout settings.

The example logic is like this

export default defineNuxtRouteMiddleware((to, from) => { const user = useUserStore(); if (!user && to.meta.layout === auth) { return navigateTo("/login"); } });

Hope this helps

    P粉478445671

    you can not. Middleware only works on pages.

    Instead, create a parent Page component using the auth middleware and theNuxtPagecomponent inside the template. For more information onNested Routing, see the Nuxt 3 documentation.

    Example:

    /pages/admin.vue(Route =>/admin)

               sssccc

    /pages/admin(folder)

    admin/order.vue routing =>/admin/orders

    admin/page.vue route =>/admin/some-route

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!