【vue】封装vue3组件注意事项

封装组件注意事项有哪些?

1.组件是单向数据流,杜绝使用ref从父级操作子级内的数据和函数
错误示例

#父级
<template>
	<div>
		<child ref="childRef"/>
	</div>
</template>
<script setup>
let childRef = ref()
onMonthed(()=>{
    
    
childRef.value.data = "修改子级数据"
})
</script>


#子级
<template>
	...
</template>
<script setup>
let data = ref("测试")
</script>

正确示例

#父级
<template>
	<div>
		<child ref="childRef"/>
	</div>
</template>
<script setup>
let childRef = ref()
onMonthed(()=>{
    
    
childRef.value.handleChange()
})
</script>


#子级
<template>
	...
</template>
<script setup>
let data = ref("测试")

const handleChange = ()=>{
    
    
	data.value = "修改" 
}

#暴露handleChange函数,让父级操作
expose({
    
    handleChange})
</script>

猜你喜欢

转载自blog.csdn.net/qq_36977923/article/details/130490298