关于vue3.0语法糖里,父组件修改子组件的值或者调用方法,主要需要defineExpose这个方法,将数据和方法暴露出来
<template>
<!-- 子组件 children.vue -->
<div v-if="showTip">{{text}}</div>
</template>
<script setup>
// 导入子组件
import { ref, defineExpose } from 'vue'
const showTip = ref(false);
const text = ref('我是子组件');
const changeFun = ()=>{
showTip.value = true;
}
defineExpose({
text,
changeFun,
}); //这里是关键
</script>
<template>
<!-- 父组件 -->
<button @click="showChildren">展示子组件</button>
<children ref="childrenRef" />
</template>
<script setup>
// 导入子组件
import { ref } from 'vue'
import children form './children'; //引入子组件
const childrenRef = ref(null);
const showChildren = ()=>{
childrenRef.value.changeFun();
childrenRef.value.text = '父组件修改了子组件';
}
</script>