Change default layout programmatically

russellsean
0
russellsean
commented 9 months ago

What problem does this feature solve?

Role-based applications could load different layouts based on the user's role. Currently, I am utilizing the layout property in every component like:

  layout(context) {
    return context.store.state.auth.user.role
  } 

my layout folder is structured like:
layout/

  • admin.vue
  • default.vue
  • manager.vue
  • norole.vue
  • user.vue

Which works great until I create a new component and forget to throw this snippet in.

What does the proposed changes look like?

I am wondering if having a global method to set the default layout would be a useful feature. In the scenario of programmatically changing the layout based on a user's role, I would image it would be called like:

this.$layout.setDefault(this.$auth.user.role + '.vue'); // admin role -> admin.vue
// or maybe even bind it?!
this.$layout = this.$auth.user.role + '.vue';

Maybe I am overthinking this. Thanks!

idea
0
Timkor
6
Timkor
commented 9 months ago

I think that's already possible:

$nuxt.setLayout('admin')

You could just watch the store.state.auth.user.role and change layout.

0
russellsean
0
russellsean
commented 8 months ago

Thank you! Do you know of any way I can access this.$nuxt from within vuex?

0
manniL
6.7k
manniL
commented 8 months ago

@russellsean on client-side: window.$nuxt.

0
manniL
6.7k
manniL
commented 8 months ago

PS: Closing here as the requested feature is already included.

0
russellsean
0
russellsean
commented 8 months ago

I noticed this only changes for the current component. If you route to another page it changes back to the default layout. Is there any way to change the default layout for the entire app?

0
altryne
0
altryne
commented 6 months ago

Jumping in here, is there a way to use setLayout from inside asyncData?
All I found is accessing context.app.methods.setLayout but it doesn't change the actual layout of the printed page.

0
marko-mlinarevic
0
marko-mlinarevic
commented 3 months ago

@russellsean @altryne did you find the solution?

0
russellsean
0
russellsean
commented 3 months ago

@marko-mlinarevic negative. I took a different approach. I use the same layout for authenticated users, but load components based on their role.

0
marko-mlinarevic
0
marko-mlinarevic
commented 3 months ago

@russellsean I did a hacky solution.

when landing on page I do this in fetch

          beforeNuxtRender(({ nuxtState }) => {
            nuxtState.layout = store.state.layout;
          })

and when changing pages I do this in created

    this.$nuxt.setLayout(this.$store.state.layout)

It works for now

0
Informations
Feature Request โ€ข Open
#c8764 - Created 9 months ago