Home > front end >  How to get the current nuxt layout from within a component/template?
How to get the current nuxt layout from within a component/template?

Time:10-08

Nuxt provides a way to dynamically set a layout within a component, but is there a way to determine which layout is in use from within the <template> e.g. v-if="layout === 'me'"? For example, I want to use a single route /c/dream and provide one layout for a user who is authenticated and another layout for a user who is not authenticated. If I can determine the layout in use from within the template, then I can structure the HTML according to the layout. I've inspected the this object in a component and do not see a way to determine which layout is in use.

CodePudding user response:

One way is to rely on Vue provide/inject feature to pass down this information to all child components.

Your layouts would provide the name of the layout:

// layouts/authenticated.vue
export default {
  provide() {
    return { layout: "authenticated" };
  },
};

Your page components or any child component can inject layout to determine which layout is currently in use.

// pages/c/dream.vue
<template>
  <div>
    <div v-if="layout == 'authenticated'">
      <!-- custom UI for authenticated users -->
    </div>
  </div>
</template>

<script>
export default {
  // Determines which layout is currently in use
  inject: ["layout"],

  // Decide which layout to use
  // based on Nuxt context as an example
  layout(context) {
    return context.user ? "authenticated" : "default";
  },
};
</script>

I have to admit, it's strange to implement layout(context) in order to set the layout we want to use and have to inject layout to access the value in the same component.

  • Related