如何在NuxtJS中向页面添加动态opengraph元数据

问题描述 投票:0回答:1

我将 NuxtJS 与 Nuxt3 一起使用,在我的组件中,我想使用动态 opengraph 元数据更新页面的头部。在我的组件中,我显示了一个图库,为此我从异步 API 中获取数据。由于我面对来自 API 的数据,因此需要一些时间才能将数据挂载到组件中。

但是,在 nuxt.config.ts 文件中,我已经为网站登陆页面或不需要显示动态 opengraph 元数据的任何其他页面定义了带有 hasd 编码数据的元标记 -

export default defineNuxtConfig({
  //SEO
  app: {
    head: {
      title: 'Talking Lands',
      charset: 'utf-8',
      viewport: 'width=device-width, initial-scale=1',

      meta: [
        { charset: 'utf-8' },
        { name: 'viewport', content: 'width=device-width, initial-scale=1' },
        { hid: 'description', name: 'description', content: '' },
        { hid: 'og-title', property: 'og:title', content: 'Vuetify + Nuxt'},
        { hid: 'og-type', property: 'og:type', content: 'website' },
        { hid: 'twitter-card', property: 'twitter:card', content: '' },
        { hid: 'og-image', property: 'og:image', content: 'https://new.example.com/static-assests/images/TLlogo_Dark.svg'},
        { hid: 'og-description', property: 'og:description', content: 'This is amazing example of opengaph protocols made using Nuxt and Vuetify'},
        { name: 'format-detection', content: 'telephone=no' }
      ],
    },
    pageTransition: { name: 'page', mode: 'out-in' },
  },
// ... other configurations

在组件中,我正在使用脚本设置,并且我正在使用 NuxtJS 的 useHead 属性更新头部,如下所示 -

<script setup>
// ... other code
useHead({
    title: projName,
    meta: [
        { hid: 'og-title', property: 'og:title', content: projName },
        { hid: 'og-image', property: 'og:image', content: projImage || 'loading-image-url' },
        { hid: 'og-description', property: 'og:description', content: projDescription }
    ],
})
// ...other code and api calls
<script>

projName、projDescription 和 projImage 我从 API 调用中获取并在代码的 useHead 部分中更新它们。在浏览器中,当我在本地运行时,浏览器选项卡中的标题会动态更改,但是当我检查浏览器中的元素 og:title、og:image、ig:description 时丢失。

** 甚至有时会失踪 -

<title></title>
<meta name="description" content>
<meta property="og:title" content="Vuetify + Nuxt">
<meta property="og:type" content="website">
<meta property="twitter:card" content>
<meta property="og:image" content="https://new.example.com/static-assests/images/TLlogo_Dark.svg">
<meta property="og:description" content="This is amazing example of opengaph protocols made using Nuxt and Vuetify">

它不会被更新的动态元数据覆盖,这里仅显示 nuxt.config.ts 文件中的元数据

我希望它在我从 API 获取数据后更新 html 结构,因此当在 facebook 上共享不同项目时,应该有动态的不同元数据。

我可以用什么可能的方式来更新 html 结构,以便 open-graph 可以读取更新的标签

javascript vue.js nuxt.js metadata facebook-opengraph
1个回答
0
投票

computed()
传递给
useHead
而不是静态值

在 Nuxt-Page-Component 设置中

const projName = ref('my project name') // your projName `Ref`

const computedPageMeta = computed(() => {
    return {
        title: projName.value,
        meta: [
            { hid: 'og-title', property: 'og:title', content: projName.value },
            ...
        ]
    };
});

useHead(computedPageMeta);

阅读

useHead
文档了解更多详情

© www.soinside.com 2019 - 2024. All rights reserved.