【问题标题】:VueJs CLI import/compile html string to vueVueJs CLI 导入/编译 html 字符串到 vue
【发布时间】:2025-12-20 23:55:06
【问题描述】:

我正在寻找一种解决方案,将我的 html 字符串导入到我的 VueJs 组件中,并能够执行 html 代码中存在的任何 VueJs 代码。 我正在使用 VueJs (2.5.x) + CLI 运行 vue 应用程序,运行几秒钟后,它向 API 发出请求以检索 HTML 代码。

HTML代码(导入并点击卡片后,我应该可以更改accessCardId数据):

<div class="md-card md-theme-default" v-on:click="accessCardId = '5bfc54cf553b485038333ee5'">
        <div class="md-card-media">
          <img src="/icons/europa.jpg" alt="People" class="icon">
        </div>
        <div class="md-card-header">
          <div class="md-title">Europa</div>
          <div class="md-subhead">Every where, you can us...</div>
        </div>
      </div>

VueJs 脚本(在 home.vue 中):

<script>
  export default {
    name: 'Home',
    props: {
      msg: String
    },
    data: () => ({
      listCards: null,
      currentPage: -1,
      accessCardId: null
    }),
    filters: {
      shortDescription: description =>
        `${description.substring(0, 150)}${description.length > 150 ? '...' : ''}`
    },
    methods: {
      async loadPage() {
        await this.$http.get(`${process.env.VUE_APP_SERVER_URL}/icos?token=${process.env.VUE_APP_SERVER_TOKEN}&page=${this.currentPage + 1}`)
          .then(async res => {
            this.currentPage = this.currentPage + 1;
            // res.body === my html code
          });
        }
      }
    }
</script>

【问题讨论】:

    标签: html templates vue.js compilation


    【解决方案1】:

    您可以使用v-htmldirective,它用于呈现不需要任何事件处理或数据绑定的静态html内容,根据official doc

    span 的内容将替换为 rawHtml 属性的值,解释为纯 HTML - 数据绑定被忽略。请注意,您不能使用 v-html 来编写模板部分,因为 Vue 不是基于字符串的模板引擎。相反,组件更适合作为 UI 重用和组合的基本单元

    另一种解决方案是使用https://github.com/alexjoverm/v-runtime-template 中的包v-runtime-template

    这可能对您的用例有用,因为通常担心这些方法对恶意注入的安全性。

    【讨论】:

    • 我试过了,但它不起作用。点击事件会被忽略,而且 VueJs 不会解释它。 you cannot use v-html to compose template partials, because Vue is not a string-based templating engine
    • @user9529080 我通过添加一些细节更新了我的答案
    • 您应该在模板中添加一个根元素,例如 &lt;template&gt;&lt;div&gt;all the content&lt;/div&gt;&lt;/template&gt; 而不是 &lt;template&gt;&lt;div&gt;some content&lt;/div&gt;&lt;div&gt;some other content&lt;/div&gt;&lt;/template&gt;
    • 它不适用于&lt;template&gt;&lt;div&gt;&lt;/div&gt;&lt;/template&gt;,但是当删除&lt;template&gt; balise 时它可以工作!谢谢 !例如:&lt;div&gt;all content&lt;/div&gt;