vue.js 在页面的特定位置插入HTML而不需要额外的div元素?

toiithl6  于 2023-08-07  发布在  Vue.js
关注(0)|答案(2)|浏览(133)

我正在寻找一种方法来插入一个HTML字符串在一个特定的位置在我的网页上,而无需添加额外的元素。目前,我使用以下代码:

<template v-html="myHtml">
</template>

字符串
然而,这种方法似乎并不奏效。我知道我需要使用一个HTML元素,比如一个div,但是我想避免在我的标记中添加一个额外的div。如何在不需要额外div的情况下实现这一点?
值得注意的是,该解决方案应该支持服务器端呈现(SSR),这意味着我不能依赖于使用文档或任何类似的客户端方法。

xeufq47z

xeufq47z1#

你应该把HTML编译成一个组件,然后用<Component>把它插入到一个模板中:
https://vuejs.org/guide/essentials/component-basics.html#dynamic-components
具体如何做到这一点一步一步我在这里描述:
Custom markup language JSON to vue

epfja78i

epfja78i2#

正如 Alexandria 所建议的,您可以使用一种称为dynamic component rendering的技术。这允许您在所需位置插入HTML,而无需添加额外的div。
示例**:**

<template>
  <component :is="myHTMLComponent"></component>
</template>

<script>
export default {
  data() {
    return {
      myHTMLComponent: null,
      myHtml: '<h3>This is HTML string</h3>'
    };
  },
  mounted() {
    // Create a component with the provided HTML string.
    const HTMLComponent = {
      template: this.myHtml
    };

    this.myHTMLComponent = HTMLComponent;
  }
};
</script>

字符串

相关问题