'In Nuxt, how do you pass data from layouts to pages?
For example, in my /layouts/sidebar.vue
I have the following code:
<template>
<div class="mainContainer">
<nuxt :date-sidebar="'This is from sidebar'"/>
</div>
</template>
I want to pass the value of date-sidebar
from layouts to /pages/Request/index.vue
and eventually to /components/RequestTable.vue
but I'm just currently testing it by passing static strings with the following code:
<template>
<div>
<RequestTable :date-requested="'something'"/>
{{ this.dateSidebar }} //data from sidebar that should receive something also tried just {{dateSidebar}}
</div>
</template>
<script>
export default{
props:['dateSidebar']
}
</script>
I can receive the static value from /page/Request/index.vue
to my /components/Request/RequestTable.vue
but I can't receive the data from the /layouts/sidebar.vue
to my /pages/Request/index
.
So my question as the title suggest would be, how do I pass date-sidebar
from /layouts/sidebar.vue
to /pages/Request/index
.
Solution 1:[1]
As far as I know, this only works with nuxt-link
(in pages so) as shown here and not nuxt
pages/child.vue
<template>
<nuxt-child :test="'RESOLVE_PLZ'"/>
</template>
pages/child/index.vue
<script>
export default {
props: ["test"],
mounted() {
console.log(this.test) // RESOLVE_PLZ
}
}
</script>
It is kinda logical because the default layout is not really aimed towards this kind of usage. If you need something dynamic, it's usually going the other way around (emitting to the layout) or simply using Vuex (mainly because of not having to "emit up" several components up).
You could also do some hacky things like this
child.vue
<template>
<div>
{{ dateSidebar }}
</div>
</template>
<script>
export default {
computed: {
dateSidebar() {
return this.$parent.$attrs['date-sidebar']
}
},
}
</script>
But this is not that common, hence probably not the way to do it.
Solution 2:[2]
You need to use the nuxtChildKey
props in your child properties. From the layout, bind the nuxt-child-key
instead of :date-sidebar
.
You may want to pass an object instead of a string so you can pass more data. So your layout/sidebar
would look like...
<template>
<div class="mainContainer">
<nuxt :nuxt-child-key="'This is from sidebar'"/>
</div>
</template>
On the child page...
<template>
<div>
<RequestTable :date-requested="'something'"/>
{{ this.dateSidebar }} //data from sidebar that should receive something also tried just {{dateSidebar}}
</div>
</template>
<script>
export default{
props:['nuxtChildKey'],
mounted(){
console.log(this.nuxtCHildKey, 'nck')
}
}
</script>
And there's a documentation available here... nuxt-child-key
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kissu |
Solution 2 | DAVID AJAYI |