如何使用 nuxt 访问组件中的 HEAD 数据?

How can I access HEAD data in component with nuxt?

在一个页面中,我这样设置标题:

...
<script>
export default {
  head() {
    return {
      title: this.post.name
    }
  }
}
</script>

如何在另一个组件中获取此数据?

我尝试使用 this.$metaInfo,但我需要获取数据的组件位于 <nuxt />...
之外的布局中 此外,如果当前路由在 child 页面中且头部已填充,则它会覆盖 parent 标题。那么,我该怎么办?

this.$metaInfo 将只能在页面组件中访问。如果您想在任何地方使用当前页面的标题,我认为最好的方法是使用 store 保存当前标题,然后在任何组件中轻松检索此信息。

store/index.js

export const state = {
  title: 'Default Title'
}

export const mutations = {
  SET_TITLE (state, title) {
    state.title= title
  }
}

然后在 页面组件上使用它

<template>
  <div></div>
</template>

<script>
export default {
  head () {
    return {
      title: this.title
    }
  },
  mounted () {
    this.$store.commit('SET_TITLE', this.$metaInfo.title)
  }
}
</script>

现在,您可以在从商店状态检索的任何组件中访问当前标题。

<template>
  <div></div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState({
      title: state => state.title
    })
  }
}
</script>

您可以沿着组件树往上走,直到到达页面组件

metaInfoTitle() {
  let curr = this
  let title = null
  do {
    title = curr?.$metaInfo?.title
    curr = curr.$parent
  } while (!title && curr)
  return title
},