0

I'm working on a Vue / Gridsome project and wondering how to export a variable from within a Page to it's parent Layout.

Here is my page code:

<template>
  <Layout>
    <h1>About us</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error doloremque omnis animi, eligendi magni a voluptatum, vitae, consequuntur rerum illum odit fugit assumenda rem dolores inventore iste reprehenderit maxime! Iusto.</p>
  </Layout>
</template>

<script>
export default {
  metaInfo: {
    title: 'About us'
  }
}
</script>

How can I export a custom property like Author as an example?

I'd like to output that property on the Layout:

<template>
    <h1>{{ page.author }}</h1>
    <slot/>
</template>

<script>
import SiteHeader from '@/components/SiteHeader.vue'
import SiteFooter from '@/components/SiteFooter.vue'

export default {
  components: {
    SiteHeader,
    SiteFooter
  }
}
</script>

<static-query>
query {
  metadata {
    siteName
  }
}
</static-query>
jermainecraig
  • 311
  • 4
  • 20

2 Answers2

1

You could use the $emit function to achieve this.

Inside child component:

$emit('custom-event', 'my value')

Then in your parent you can listen for this event and catch the value.

@custom-event="myMethod"

And with a method:

methods: {
    myMethod (value) {
        console.log(value);
    }
}

This should log 'my value'

You can read more about custom events here:

https://v2.vuejs.org/v2/guide/components-custom-events.html

tony19
  • 125,647
  • 18
  • 229
  • 307
T. Short
  • 3,481
  • 14
  • 30
0

Vue uses unidirectional data-flow. Hence there is no way to update data "from below".

The workaround is to use named slots.

So your layout should look like


<template>
    <h1><slot name="author">Here is a default (fallback) content that would be replaced with content passed into slot. And it is optional.</slot></h1>
    <slot/> <!-- this is a default slot -->
</template>

And your page component should look like

<template>
  <Layout>
    <template v-slot:author>author here</template>
    <h1>About us</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error doloremque omnis animi, eligendi magni a voluptatum, vitae, consequuntur rerum illum odit fugit assumenda rem dolores inventore iste reprehenderit maxime! Iusto.</p>
  </Layout>
</template>
Ivan Klochkov
  • 705
  • 4
  • 14