Reputation: 4714
In a page, I set head title like this:
...
<script>
export default {
head() {
return {
title: this.post.name
}
}
}
</script>
How can I get this data in another component?
I tried with this.$metaInfo
but my component where I need to get data is in the layout outside <nuxt />
...
Also, If the current route is in a child page with populated head, it's override the parent title. So, how do I do?
Upvotes: 6
Views: 6651
Reputation: 553
you can walk up the component tree until you reach the page-component
metaInfoTitle() {
let curr = this
let title = null
do {
title = curr?.$metaInfo?.title
curr = curr.$parent
} while (!title && curr)
return title
},
Upvotes: 0
Reputation: 620
this.$metaInfo
will be accessible just in the page component. If you want to have the title of the current page anywhere, I think the best way is using the store
to save the current title then retrieve this information easily in any component.
In store/index.js
export const state = {
title: 'Default Title'
}
export const mutations = {
SET_TITLE (state, title) {
state.title= title
}
}
Then use this on the pages components
<template>
<div></div>
</template>
<script>
export default {
head () {
return {
title: this.title
}
},
mounted () {
this.$store.commit('SET_TITLE', this.$metaInfo.title)
}
}
</script>
Now, you can access the current title in any component you are retrieving it from the store state.
<template>
<div></div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
title: state => state.title
})
}
}
</script>
Upvotes: 5