很多人不知道megreProps的用法,今天我们就来讲解下mergeProps的用法以及原理
1.用法
大家觉得下面哪种用法是正确的呢?
这样
style: mergeProps({
width: this.itemWidth
}, xProps.style)
或者这样
style: mergeProps({
style: {
width: this.itemWidth
},
...(xProps?.style ?? {
})
})
还是这样
style: mergeProps(
{
style: {
width: this.itemWidth },
},
xProps,
).style
你使用的话会使用上面哪一种呢?
不知道
因为写的是jsx语法,所以查看了vue3的jsx语法,发现里面并没有关于这个解释,只说到了默认开启
于是去vue3官网查找,找到megreProps:Merge multiple props objects with special handling for certain props.
意思就说合并多个道具对象,对某些道具进行特殊处理
所以前面两种写法是错误的
接着看了下mergeProps源码的写法
// ...args将多个对象收集成数组
export function mergeProps(...args: (Data & VNodeProps)[]) {
// 最终合并的结果
const ret: Data = {
}
// 遍历用户传入的多个对象
for (let i = 0; i < args.length; i++) {
// 取到传入的对象值
const toMerge = args[i]
for (const key in toMerge

本文探讨Vue3中mergeProps的用法及其原理,解析了mergeProps如何处理特定道具,指出常见错误用法,并通过源码分析强调了需要包含style、class等关键属性。同时,详细介绍了normalizeClass和normalizeStyle函数的作用,帮助理解如何处理class和style属性,以提高Vue3应用开发的熟练度。


被折叠的 条评论
为什么被折叠?



