<template>
  <div>
    <ChildComponent ref='child' />
    <button @click='handleClick'>调用子组件方法</button>
  </div>
</template>
<script>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'

export default {
  components: {
    ChildComponent
  },
  setup() {
    const childRef = ref(null)
    
    const handleClick = () => {
      childRef.value.doSomething()
    }
    
    return {
      childRef,
      handleClick
    }
  }
}
</script>
<p>在上述代码中,我们通过 <code>ref</code> 创建了一个名为 <code>childRef</code> 的响应式引用,并将其赋值为 <code>null</code>。然后,在模板中,我们将子组件 <code>ChildComponent</code> 的实例赋值给 <code>childRef</code>,并在父组件中定义了一个名为 <code>handleClick</code> 的方法,在该方法中使用 <code>childRef.value</code> 来获取子组件实例,并调用其 <code>doSomething</code> 方法。</p>
<p>需要注意的是,在 <code>setup</code> 函数中,<code>childRef</code> 是响应式的,因此我们使用 <code>childRef.value</code> 来获取子组件实例,而不是 <code>childRef</code> 本身。</p>
Vue 组合式 API:父组件触发子组件方法

原文地址: https://www.cveoy.top/t/topic/nwG2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录