最近研究一个vue3
项目,自己也看了一下vue3
的相关文档,发现一些问题,不太确认,来请教下,假设代码如下:
const props = defineProps({
attr: {
type: Object,
required: true
}
})
//vue3 代码
const { width, height } = toRefs(props.attr)
我解读上面vue3
代码的意思:
通过props
属性attr
对象的属性定义相同的width
、height
属性,并且给定义好的data属性width
、height
通过attr属性对象赋初始值;
翻译成vue2
代码为:
props: {
attr: {
type: Object,
required: true
}
},
data() {
return {
width: this.attr.width,
height: this.attr.height
}
}
通过调试 vue3
项目时我发现,不管是修改width
属性还是attr对象的width
属性,他们都会相互影响,也就是说,width
、attr.width
根本就是一个东西
,那么转换成如上的 vue2
代码那就是错误的,更像是(vue2)定义了两个computed
属性width
、height
,只不过这两属性可以直接在vue3代码中通过v-model来绑定并修改。
请问我理解的意思有啥问题吗?
你的代码相当于把props.attr用ref包裹了一层,然后把width和height通过解构的方法提取出来。所以attr.width和width的指向其实是相同的。