NUXT how to pass data from page to layout

Viewed 15282

I am creating a very simple website. I want to change the Navbar elements depending on data set in navLayout on the page template. I want to pass the data to the layout, then use props to send it to the NavBar. My issue is how to emit data from the page to the layout.

layouts/default.vue

<template>
  <div>
    <NavBar />
    <div class="site-container">
      <nuxt />
    </div>
    <Footer />
  </div>
</template>
<script>
import NavBar from '~/components/NavBar.vue'

export default {
  components: {
    NavBar,
  }
}
</script>

pages/index.vue

...
<script>
export default {

  data: () => {
    return {
      navLayout: 'simple'
    }
  },
  computed: () => {
    return {
    this.$emit('navLayout', value)
    }

  }
...
</script> 
2 Answers

One option is to use vuex for that.

First go into the store folder in your nuxt project and create a index.js file

export const state = () => ({
   layout: 'Your default value',
})
    
export const mutations = {
  CHANGE_NAV_LAYOUT(state, layout) {
    state.layout = layout;
  }
}

Then inside any page/component you can call this.$store.commit('CHANGE_NAV_LAYOUT',value)

For your navbar component you create a computed property and refer it to the store layout value:

computed: {
     navLayout() {
         return this.$store.state.layout;
     }
}

You should use $emit from parent element, so the parent element to the page is layout page. Here is sample:

this.$parent.$emit("eventName");

Then listen action at layout on the Nuxt component.

<Nuxt @eventname="actionHandler()"/> 

And here it is)

Related