使用h()渲染函数的条件渲染组件在props变更时未重新渲染
问题原因
你当前的代码里,setup函数只会在组件初始化时执行一次。if (!props.useWrapper)这个条件判断是在setup阶段执行的,一旦返回了某个渲染函数,后续useWrapper变更时,setup不会重新执行,所以渲染函数不会更新,组件自然不会重新渲染。
解决方案
有两种常见的修复方式:
方式一:将条件判断移入渲染函数内部
把条件逻辑放到返回的渲染函数里,这样每次组件渲染时都会读取最新的props.useWrapper值,触发响应式更新:
<script lang="ts"> import { h } from 'vue'; export default defineComponent({ props: { useWrapper: { type: Boolean, default: true } }, setup (props) { watch(() => props.useWrapper, (newValue) => { console.log('useWrapper changed: ' + newValue + ' - rerender'); }); // 把条件判断放在返回的渲染函数里 return () => { if (!props.useWrapper) { return h('div', {}, 'Some funny content'); } return h('div', {}, 'Other content'); }; } }); </script>
方式二:使用computed包装渲染内容(可选)
如果渲染逻辑更复杂,可以用computed来追踪依赖,返回对应的VNode:
<script lang="ts"> import { h, computed } from 'vue'; export default defineComponent({ props: { useWrapper: { type: Boolean, default: true } }, setup (props) { watch(() => props.useWrapper, (newValue) => { console.log('useWrapper changed: ' + newValue + ' - rerender'); }); const renderContent = computed(() => { if (!props.useWrapper) { return h('div', {}, 'Some funny content'); } return h('div', {}, 'Other content'); }); return () => renderContent.value; } }); </script>
原理说明
Vue的响应式系统需要在渲染函数(或computed、watch)内部访问响应式变量,才能追踪依赖并触发更新。你之前的写法是在setup的同步代码里访问props.useWrapper,这只会执行一次,不会建立后续的依赖追踪,所以props变更时无法触发渲染函数的更新。
内容的提问来源于stack exchange,提问作者Galivan
相关产品推荐
相关产品推荐

