【问题标题】:What's the right way to bind OG tags in a dynamic Vue 3 App?在动态 Vue 3 App 中绑定 OG 标签的正确方法是什么?
【发布时间】:2021-06-29 07:32:25
【问题描述】:

我有一个动态页面,我需要在其中发出 API 请求并动态更新元标记。

我可以通过在App.js 中添加 API 请求并根据 API 的响应更新 HTML 头部标签来实现。

当我在社交媒体上分享 URL 时,标签没有显示,因为它需要一些加载时间。

我的应用程序有很多带有许多路由的动态页面。但是,从 SEO 的角度来看,路线中只有 1 条路径对我来说很重要。

在社交媒体上共享时,我应该采取什么方法来显示元标记?

【问题讨论】:

  • 你试过使用 vue-meta npmjs.com/package/vue-meta吗?
  • @BoussadjraBrahim 知道如何在 Composition API 中将它与 VueRouter 一起使用吗?我在我的组件中尝试了import VueMeta from 'vue-meta'Vue.use(VueMeta, { refreshOnceOnNavigation: true }) ,并使用了引用变量metaInfo。但这似乎不起作用。关于如何在 Composition API 中使用它的任何想法?

标签: vue.js vue-router meta-tags vuejs3


【解决方案1】:

vue-meta 插件现在兼容 vue 3

安装:

npm install vue-meta@next --save

用法:

main.js

import { createApp} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import VueMeta from 'vue-meta'

let app = createApp(App)

let root = app.use(VueMeta ,{refreshOnceOnNavigation:true}).use(store).use(router).mount('#app')

在任何子组件中:

import { watch } from 'vue'
import { useMeta, useActiveMeta } from 'vue-meta'

export default {
  setup () {
    const counter = ref(0)

    // Add meta info
    // The object passed into useMeta is user configurable
    const { meta } = useMeta({
      title: 'My Title',
    })

    watchEffect(() => {
      const counterValue = counter.value
      meta.description = `Counted ${counterValue} times`
    })

    // Or use a computed prop
    const computedMeta = computed(() => ({
      title: 'My Title',
      description : `Counted ${counter.value} times`
    }))

    const { meta, onRemoved } = useMeta(computedMeta)

    onRemoved(() => {
      // Do something as soon as this metadata is removed,
      // eg because the component instance was destroyed
    })

    // Get the currently used metainfo
    const metadata = useActiveMeta()

    watch(metadata, (newValue) => {
      // metadata was updated, do something
    })
  }
}

更多详情请查看branch

【讨论】:

  • 它要求我安装软件包 - @vue/server-renderer。安装并重新运行应用程序后,我遇到了这个错误 - Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
  • 因为这只是一个警告,所以我忽略了它。当我尝试在组件文件中引用 useMeta 时,我不断收到此错误 Uncaught (in promise) Error: No manager or current instance
猜你喜欢
  • 2021-11-21
  • 2022-12-03
  • 1970-01-01
  • 2020-04-12
  • 2011-01-06
  • 2014-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多