defineExpose(父拿子方法)

在vue2中是使用this.refs.子组件名称.xxx方法,即可拿到子组件定义的值或者方法,在vue3中没办法这么拿取,必须子组件暴露后父组件才可以拿取到

//子组件
<template>
    <div class="child">
        {{val}}
    </div>
</template>
<script setup>
import {ref,defineExpose} from 'vue'
let val = ref('我是子组件')
let fn = ()=>{
    val.value='我改变了子组件'
}
// 暴露val和fn
defineExpose({
    val,fn
})
</script>
​
​
​
//父组件
<template>
  <div class="box">
    <!-- 接收子组件的方法 -->
    <v-child ref ='child'></v-child>
  </div>
</template>
<script setup>
// 引入后无需注册
import vChild from "../components/child.vue";
import {ref,onMounted} from 'vue';
// 获取child实例
let child = ref()
onMounted(()=>{
  console.log(child.value.val);//直接打印:我是子组件,并不需要加.value
  // 执行子组件的fn函数
  child.value.fn()
})
</script>


posted @ 2023-03-27 16:40  Felix_Openmind  阅读(716)  评论(0)    收藏  举报
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}