vue-composition-api 中的 Refs 方法

Refs methods in vue-composition-api

有一个组件的引用如下:

<template>
  <custom-component
     ref="func"
  />
</template>

<script setup>
const func = ref();
</script>

在组件内部有一个这样的函数:

const helloWorld = () => {
    console.log('hello World');
}

如何从父组件访问 helloWorld 函数?

假设您的子组件也在使用 <script setup>,组件的定义默认关闭(未公开)。

您可以在子组件中手动暴露带有defineExpose的方法:

// CustomComponent.vue
<script setup>
const helloWorld = /*...*/

defineExpose({
  helloWorld
})
</script>

demo