vue.jsnuxt.jsvue-props

How to pass prop from page to layout


I currently have duplicated layout that the only difference is a prop I pass to a component:

default.vue

    <template>
      <div class="page">
        <SkipToContent />
        <Header />
        <Nuxt />
        <Footer />
      </div>
    </template>

front.vue

    <template>
      <div class="page">
        <SkipToContent />
        <Header light="true" />
        <Nuxt />
        <Footer />
      </div>
    </template>

Is there any way to pass that light: true from page to layout so I can use only default.vue layout?

I know I could emit some event on mounted but would like to prevent using lifecycle hooks for this


Solution

  • Passing data up from a child is ideally done by emitting events, and you don't need to use lifecycle hooks for that (a custom event listener would work).

    But I think a cleaner solution would be to factor out the common markup into a component that receives a light prop, and use them in both layouts:

    <!-- components/CommonLayout.vue -->
    <template>
      <div class="page">
        <SkipToContent />
        <Header :light="light" />
        <Nuxt />
        <Footer />
      </div>
    </template>
    
    <script>
    export default {
      props: {
        light: Boolean,
      }
    }
    </script>
    
    <!-- layouts/default.vue -->
    <template>
      <CommonLayout />
    </template>
    
    <!-- layouts/front.vue -->
    <template>
      <CommonLayout light />
    </template>
    

    demo