Vue3编译动态HTML时嵌套场景下如何正确定义所需属性?
问题原因
- 作用域不匹配:通过
compileAPI编译生成的模板,运行时的作用域绑定的是dyno-html组件内部实例,而非调用dyno-html的父组件实例。你在动态模板中写的:htmlTxt='htmlTest2'会默认到dyno-html实例上找htmlTest2属性,该属性未定义就会触发告警,后续模板编译失败就会抛出template is undefined错误。 - 嵌套组件变量未透传:第二层嵌套的
dyno-html同样需要访问对应的变量,没有透传对应作用域数据的情况下也会出现同类型的作用域访问错误。
解决方案
调整dyno-html组件,新增scope参数用来接收外部传入的作用域变量,将变量挂载到编译生成的组件实例上,修改后的组件代码如下:
app.component("dyno-html", { props: ["htmlTxt", "scope"], setup(props) { const textCompRef = computed(() => ({ // 将外部传入的作用域变量挂载为当前编译组件的响应式数据 data() { return props.scope || {} }, render: compile(props.htmlTxt) })); return () => h(textCompRef.value); }, });
父组件调用时,把需要用到的变量通过scope参数透传给dyno-html,嵌套调用时也需要同步透传内层需要的变量:
<template> <div class="home"> <dyno-html :htmlTxt="htmlTest" :scope="{ htmlTest2 }"></dyno-html> </div> </template> <script> export default { name: "Home", data() { return { htmlTest: "<h1>Test</h1><dyno-html :htmlTxt='htmlTest2' :scope='{ htmlTest2 }'></dyno-html>", htmlTest2: "<h2>Test2</h2>", } } } </script>
注意事项
- 确保项目使用的是带编译器的完整版Vue,或是在Vue配置中开启了
runtimeCompiler: true,否则compileAPI无法正常运行。 - 如果嵌套层级较多,可以把所有需要用到的变量统一挂载到
scope中传入,避免逐层传参的繁琐。
内容的提问来源于stack exchange,提问作者Ace
相关产品推荐
相关产品推荐

