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

如何在Nuxt3/Vue3中渲染包含Vue元素的HTML字符串

解决Nuxt3中渲染含Vue语法的HTML字符串问题

问题根源分析

  1. TypeError: h is not a function:Vue3选项式API的render函数不再自动注入h函数,需手动从vue导入。
  2. 导入h后内容不渲染:Nuxt3默认使用Vue运行时版本(不含模板编译器),无法编译动态传入的模板字符串;同时父组件的变量/方法无法直接被动态模板访问。

解决方案步骤

1. 配置Nuxt3启用Vue运行时编译器

在nuxt.config.ts中添加配置,让Vue使用带编译器的版本:

export default defineNuxtConfig({
  vue: {
    compilerOptions: {
      runtimeCompiler: true
    }
  }
})

2. 重写RenderVueString组件插件

修改plugins/RenderVueString.js,使用Vue的compile函数处理动态模板,并支持传递作用域:

import { h, compile } from 'vue'

export default defineNuxtPlugin(nuxtApp => {
  nuxtApp.vueApp.component('RenderVueString', {
    props: {
      html: {
        type: String,
        required: true
      },
      scope: {
        type: Object,
        default: () => ({})
      }
    },
    render() {
      // 编译传入的HTML模板字符串
      const renderFn = compile(`<div class="RenderVueString">${this.html}</div>`)
      // 传入作用域,让模板能访问父组件的变量和方法
      return renderFn({ ...this.scope })
    }
  })
})

3. 修改页面传递作用域

更新pages/index.vue,将需要在动态模板中访问的变量和方法打包成作用域对象传递给组件:

<template>
  <RenderVueString :html="vueHTML" :scope="componentScope" />
</template>

<script setup>
import { reactive } from 'vue'

const testVar = 'Var Value Here'

const testFunction = () => {
  console.log('test function ran')
}

// 打包模板需要访问的变量和方法
const componentScope = reactive({
  testVar,
  testFunction
})

const vueHTML = `<div>This is some vue HTML {{testVar}} <a @click="testFunction()">Run Function</a></div>`
</script>

关键注意事项

  • 启用runtimeCompiler会增大打包体积,生产环境需评估必要性。
  • 动态编译模板存在XSS风险,确保传入的html内容来自可信源,避免用户可控输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:20:35