[vue] Precautions for encapsulating vue3 components

What are the precautions for packaging components?

1. The component is a one-way data flow, and it is forbidden to use ref to manipulate data and functions in the child from the parent.
Error example

#父级
<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>

correct example

#父级
<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>

Guess you like

Origin blog.csdn.net/qq_36977923/article/details/130490298