B
B
betterthanyouthink2020-09-26 14:07:30
Vue.js
betterthanyouthink, 2020-09-26 14:07:30

How to pass parameters from page to layout nuxt js?

layouts/default.vue

<template>
  <div class="page__container">
    <app-header/>
    <main class="page__content">
      <Nuxt/>
    </main>
    <app-footer />
  </div>
</template>


In the header of this layout, I need to pass the title and subtitle, because they change depending on the page. I implemented it like this:

layouts/default.vue:
<template>
  <div class="page__container">
    <app-header :header-data="headerData"/>
    <main class="page__content">
      <Nuxt/>
    </main>
    <app-footer />
  </div>
</template>
<script>
  export default {
    name: 'default-layout',

    components: {AppHeader, AppFooter},

    computed: {
      headerData() {
        return this.$route.matched.map(r => {
          return r.components.default.options.headerData
        })[0]
      }
    }
  }
</script>


pages/index.vue and similar pages:
export default {
    headerData: {
      title: "Заголовок страницы",
      subtitle: "Подзаголовок страницы"
    }
  }


app-header.vue:
<template>
  <header>
    <h1>{{headerData.title}}</h1>
    <span>{{headerData.subtitle}}</span>
  </header>
</template>

<script>
export default {
    name: "app-header",

    props: {
      headerData: {
        type: Object,
        required: true
      }
    },
}
</script>


How correct is this decision? Can this be done more concisely?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vogordin, 2021-04-22
@vogordin

In case someone stumbles upon this old question:
If you need to pass something from the page to some other component in the layout, then it is more correct (in my opinion) in this case to use vuex and change the variable in the store if necessary. Inside the layout, you need to pull up this variable and pass it to the props of the required component.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question