Vue3如何渲染包含自定义组件标签的服务端返回动态HTML内容
直接使用v-html无法解析模板中的自定义组件和Vue指令,你可以通过Vue内置的模板编译能力实现需求,具体实现方案如下:
步骤1:使用带编译器的Vue版本
Vue默认提供的runtime-only版本不含模板编译功能,需要切换到完整版Vue。如果你使用Vite搭建项目,可在vite.config.js中添加如下别名配置:
export default { resolve: { alias: { 'vue': 'vue/dist/vue.esm-bundler.js' } } }
步骤2:封装动态渲染组件
通过compile方法编译服务端返回的HTML字符串,同时注册需要用到的ProductRow组件和传入所需参数:
import { compile, defineAsyncComponent, h } from 'vue' // 注册异步组件 const ProductRow = defineAsyncComponent(() => import("@/Component/ProductRow")) // 定义动态渲染组件 const DynamicTemplate = { props: { // 声明模板中需要用到的变量 product: { type: Object, required: true }, // 传入服务端返回的HTML字符串 templateContent: { type: String, required: true } }, components: { // 注册模板中用到的自定义组件 ProductRow }, render() { // 编译服务端返回的模板内容 const renderFn = compile(this.templateContent) return renderFn.call(this, h) } }
步骤3:组件调用
在业务代码中传入服务端返回的HTML和所需参数即可:
<template> <DynamicTemplate :template-content="serverHtml" :product="product" /> </template> <script setup> // 假设该变量为接口请求返回的HTML字符串 const serverHtml = ` <div> <product-row :product="product"/> </div> ` const product = ref({/* 你的产品数据 */}) </script>
注意事项
- 请确保服务端返回的HTML字符串为可信内容,动态编译不可信模板会存在XSS注入风险
- 模板中用到的所有自定义组件、变量都需要提前在动态渲染组件中注册、声明,否则编译过程会报错
内容的提问来源于stack exchange,提问作者BlackLotus
相关产品推荐
相关产品推荐

