vue3父组件修改子组件的值
使用 ref + expose(推荐方式)
子组件 (ChildComponent.vue):
<script setup>
import { ref } from 'vue'const childData = ref('子组件初始数据')// 暴露需要被父组件访问的数据和方法
defineExpose({childData,updateChildData(newValue) {childData.value = newValue}
})
</script>
父组件:
<template><ChildComponent ref="childRef" /><button @click="modifyChildData">修改子组件数据</button>
</template><script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'const childRef = ref(null)const modifyChildData = () => {// 直接修改子组件数据childRef.value.childData = '父组件修改后的数据'// 或者调用子组件暴露的方法childRef.value.updateChildData('父组件通过方法修改的数据')
}
</script>