如何在vue 3 ssr中动态设置jsonld

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

当我尝试通过组件 is='script' type='application/ld+json' 传递它时,出现错误: “类型错误:无法将符号值转换为字符串”,但是当我通过传送传递它时,它可以工作,但仅在客户端上有效。我使用 laravel惯性js vue3 ssr

我尝试在组件上使用 v-html

<component is='script' key='webSite' v-html='webSiteJSONLD' type='application/ld+json'></component>
,但它只是在标签脚本中插入属性innerHTML之类的数据。

以其他方式将出现错误:“TypeError:无法将符号值转换为字符串”

 <component is='script' key='webSite' type='application/ld+json'>{{ webSiteJSONLD }}</component>

文本 json const webSiteJSONLD=计算的(()=>{ 返回`{ '@context': 'https://schema.org', '@type': '网站', 'url': '${import.meta.env.SSR?import.meta.env.VITE_APP_URL:host.value}' }`; });

vue.js vuejs3 server-side-rendering inertiajs json-ld
2个回答
1
投票

我编写了惯性js的fork head组件并更改了组件中的renderTag函数。它可以工作。但是有错误

renderTag(node) {
  // check specific symbol from node.type
  switch (node.type.toString()) {
    case 'Symbol(Text)':
    case 'Symbol(v-txt)':
      return node.children
    case 'Symbol()':
    case 'Symbol(Comment)':
      return ''
    // if nothing expected, return a html string
    default:
      return this.renderTagStart(node) + 
      (node.children ? this.renderTagChildren(node) : '') +
      (!this.isUnaryTag(node) ? `</${node.type}>` : '')
  }
}

0
投票

使用以下命令创建一个新组件:

mounted () {

    const myJsonScript = document.createElement('script');
    myJsonScript.setAttribute('type', 'application/ld+json');
    myJsonScript.setAttribute('src', '...src...');
    myJsonScript.setAttribute('id', 'random_id');
    document.getElementById('app').appendChild(myJsonScript)
}

beforeDestroy () {
    document.getElementById('random_id').remove()
}

为每个属性使用 props,那么它应该接近你的需要。

在纯SSR中,你可以在模板中做这样的事情:

{{{ "&lt;script type='application/ld+json' &gt;{'key': " + value + "}&lt;/script&gt;" }}}
© www.soinside.com 2019 - 2024. All rights reserved.