提问人:Javaddict 提问时间:10/30/2023 更新时间:10/30/2023 访问量:38
vue 3 脚本设置中的最佳渲染函数
Best render function in vue 3 script setup
问:
我正在尝试以各种方式使用组合 API 和脚本设置来模仿 vue 3 中的组件行为。这是第一次尝试:<component>
<script setup lang="ts">
import {type Component, h, useSlots} from "vue";
const props=defineProps<{is:Component|string,name:string}>()
const slots=useSlots()
// @ts-ignore
const render=h(props.is,{name:props.name},slots)
</script>
<template>
<render/>
</template>
它运行良好,我可以在 devtool 中看到作为 prop 传递的“is”组件是包装器组件的直接子组件。attrs 被传递给底层的 “is” 组件,并且它对 attrs 更改做出反应。但它对道具更改没有反应:不考虑名称道具的更改。 我通过添加计算来修复它:
const render=computed(()=>h(props.is,{name:props.name},slots))
像它一样工作,但也许对 h 函数有很多调用,我担心每次发生更改时,所有 v-node 层次结构都可能被重新计算。所以也许 vue 会浪费时间来调和 v-node 和 Dom?
所以我试了一下:
const render=()=>h(props.is,{name:props.name},slots)
好的,但属性不会传递给底层的“is”组件。 所以最后我做了:
const attrs=useAttrs()
render=()=>h(props.is,mergeProps(attrs,{name:props.name}),slots)
工作完美,但我可以在开发工具中看到生成的层次结构更加复杂:包装器有一个子“渲染”组件,而该子组件又具有底层的“is”组件作为子组件。
那么,您是否知道“计算”和“mergeProps”解决方案在性能方面的最佳效果如何?看起来“mergeProps”正在复制 attrs 和 props 的 vue 内部合并,效率不是很高......但是,也许渲染速度更快,因为每次更改时都不会重新创建整个 v 节点?(但也许它也完全重新计算了?
答: 暂无答案
评论