【问题标题】:How can I access HEAD data in component with nuxt?如何使用 nuxt 访问组件中的 HEAD 数据?
【发布时间】:2020-03-09 22:44:09
【问题描述】:

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

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

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

我尝试使用this.$metaInfo,但我需要获取数据的组件位于&lt;nuxt /&gt;之外的布局中...
此外,如果当前路由位于头部填充的子页面中,它会覆盖父标题。那么,我该怎么做呢?

【问题讨论】:

    标签: vue.js nuxt.js vue-meta


    【解决方案1】:

    你可以沿着组件树向上走,直到你到达页面组件

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

    【讨论】:

      【解决方案2】:

      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>
      

      【讨论】:

      • 感谢您的回复!但我想避免使用 vuex,并为此在所有页面中写入已安装的指令。我认为这种模式重复了同样关注的代码。我发现的另一个解决方案是编写一个处理 route.meta 并填充存储的中间件。但同样,它看起来过于复杂......
      • 另外,子路由会发生什么?如果父路由和子路由commit to store,是否有冲突?
      • 嘿@ManUtopiK,您可以避免在所有组件 mounted 方法中重复代码,只需将其移动到 vue mixins 并添加到您需要的页面中.谈到子路由,在这种情况下,vuex 将使用最后一页重写。您是否考虑过为您需要的子组件中的标题添加一个 prop 并在其中传递 $metaInfo.title ?也可能是您的一个选择。
      猜你喜欢
      • 2019-03-21
      • 2020-12-17
      • 2021-12-28
      • 2020-01-14
      • 1970-01-01
      • 2020-12-11
      • 2023-02-09
      • 1970-01-01
      • 2020-09-12
      相关资源
      最近更新 更多