Vue3 setup中props无响应性 动态编译HTML无法随参数更新
Vue动态编译HTML组件不同步更新的修复方案
问题根因
原组件的setup仅在初始化时执行一次compile返回固定渲染函数,后续htmlTxt变化时,watchEffect中生成的新编译结果没有替换组件正在使用的渲染函数,因此页面不会同步更新。
修复后代码
main.js
import { ref, watchEffect, compile, h } from 'vue' app.component("dyno-html", { props: ["htmlTxt", "bound"], setup(props, ctx) { // 用响应式变量存储最新编译后的渲染函数 const latestRender = ref(() => h('div')) watchEffect(() => { console.log(`htmlText is: ` + props.htmlTxt); if (props.htmlTxt?.trim()) { latestRender.value = compile(props.htmlTxt) } else { latestRender.value = () => h('div') } }); // 返回动态包装渲染函数,每次渲染都调用最新编译结果,同时透传组件上下文保证$emit、绑定属性正常可用 return (...args) => latestRender.value.call(ctx, ...args) }, });
修复说明
- 用
ref包装编译后的渲染函数,保证其变更能被Vue的响应式系统检测到 - setup返回的是一个动态包装函数,组件每次重渲染时都会调用当前最新的编译结果
- 透传组件的上下文
ctx到渲染函数执行环境,保证模板中的$emit、bound等绑定内容能正常工作 - 增加空值判断,避免htmlTxt为空时编译报错
修改后即可正常响应htmlTxt的动态变更,异步加载HTML、点击按钮修改HTML的场景都能同步更新渲染结果,事件绑定也可正常触发。
内容的提问来源于stack exchange,提问作者Ace
相关产品推荐
相关产品推荐

