首页 资源列表 文章列表

vue3父组件调子组件方法setup写法

使用ref直接访问子组件实例

为子组件设置ref属性,父组件可通过ref.value直接调用子组件方法。

父组件模板:

<template>

 <child-component ref="childRef" />

 <button @click="callChildMethod">调用子组件方法</button>

</template>

import { ref } from 'vue';

import ChildComponent from './ChildComponent.vue';

const childRef = ref(null);

const callChildMethod = () => {

childRef.value.childMethod();

};

子组件

const childMethod = () => {

 console.log('子组件方法被调用');

};

defineExpose({

 childMethod

});