You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Vue编译自定义脚本并渲染含子组件的HTML?

在Vue中编译并渲染自定义脚本的实现方法

核心思路

Vue的compile方法可将模板字符串编译为可渲染的组件对象,再通过<component>动态组件特性渲染到页面。以下分Vue2和Vue3场景给出具体实现:


Vue2 实现方案

<template>
  <div class="user-post">
    <!-- 用动态组件渲染编译结果 -->
    <component :is="compiledComponent" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      compiledComponent: null
    };
  },
  mounted() {
    // 用反引号编写模板,避免嵌套引号转义麻烦
    const template = `Hello, please choose your variant:<br /> <pool :id='144'>`;
    // 编译模板字符串为组件对象
    this.compiledComponent = Vue.compile(template);
  },
  // 局部注册自定义组件(也可全局注册)
  components: {
    Pool: () => import("./Pool.vue")
  }
};
</script>

Vue3 实现方案

Vue3中compile需从@vue/runtime-dom单独导入,编译结果要包装为组件对象:

<template>
  <div class="user-post">
    <component :is="compiledComponent" />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { compile } from "@vue/runtime-dom";
// 导入自定义组件
import Pool from "./Pool.vue";

const compiledComponent = ref(null);

onMounted(() => {
  const template = `Hello, please choose your variant:<br /> <pool :id='144'>`;
  // 编译模板得到渲染函数
  const { render } = compile(template);
  // 包装为动态组件可识别的对象
  compiledComponent.value = {
    render,
    components: { Pool }
  };
});
</script>

关键注意事项

  • 组件注册:模板中用到的自定义组件(如<pool>)必须提前注册,支持全局或局部注册,否则会被Vue当作普通HTML标签忽略。
  • 模板语法规范:模板字符串需符合Vue模板语法要求,比如属性绑定的:id、引号使用等。
  • 安全风险:若模板内容来自用户输入,需做好XSS校验,避免恶意代码注入。

内容的提问来源于stack exchange,提问作者Rohan Warwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 21:12:46