Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUXT how to pass data from page to layout

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> 
like image 793
Simon Avatar asked Jun 25 '20 09:06

Simon


People also ask

How pass data from page to layout in NUXT JS?

You should use $emit from parent element, so the parent element to the page is layout page. Here is sample: Then listen action at layout on the Nuxt component.

Can I use vue3 with Nuxt?

It's only right that Nuxt 3 was built to support Vue 3 features. Vue 3 was released in October 2020 and has since garnered a lot of praise from the Vue community. With Nuxt 3 being written in Vue 3, you get access to features like the Composition API, better module imports, and overall improved app performance.

Is Nuxt good for spa?

When combined with headless platform such as CrafterCMS, Nuxt can provide a framework to build highly-performant web applications and SPAs. This article is an introductory review of NuxtJS, a powerful framework on top of Vue for building modern web applications.


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;
     }
}
like image 70
Badgy Avatar answered Sep 21 '22 23:09

Badgy


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)

like image 25
Сергей Паламар Avatar answered Sep 20 '22 23:09

Сергей Паламар