如何在Nuxt3/Vue3中渲染包含Vue元素的HTML字符串
解决Nuxt3中渲染含Vue语法的HTML字符串问题
问题根源分析
TypeError: h is not a function:Vue3选项式API的render函数不再自动注入h函数,需手动从vue导入。- 导入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
相关产品推荐
相关产品推荐

