How can I access HEAD data in component with nuxt?
Asked Answered
R

2

6

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?

Rightness answered 14/11, 2019 at 3:25 Comment(0)
D
5

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>
Darden answered 14/11, 2019 at 14:37 Comment(3)
Thanks for your response! But I want to avoid using vuex, and writing in all page a mounted instruction just for that. I think this pattern duplicate code with same concern. Another solution I found is write a middleware that handle route.meta and populate the store. But again, it looks overcomplicated...Rightness
Also, what's happen for sub-route? If parent route and child route commit to store, is there conflit?Rightness
Hey @ManUtopiK, you can avoid duplicating code in all component mounted methods just moving this for a vue mixins and adding in the pages you need. Talking about the sub-routes, in this context the vuex will be rewritten using the last page. Did you think about adding a prop for the title in the child components that you need this and just pass $metaInfo.title in this? May can be an option for you also.Darden
H
0

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
},
Harbaugh answered 13/7, 2021 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.