Vue3 父组件调用子组件方法
时间: 2023-11-19 08:51:59 浏览: 161
在 Vue3 中,可以通过 `ref` 和 `appContext` 来实现父组件调用子组件方法的功能。具体步骤如下:
1. 在子组件中,使用 `ref` 定义一个变量,并将需要调用的方法赋值给该变量。例如:
```vue
<template>
<div>
<button @click="handleClick">点击</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const handleClick = () => {
console.log('子组件方法被调用')
}
const childMethod = ref(handleClick)
return {
childMethod
}
}
}
</script>
```
2. 在父组件中,通过 `appContext` 获取到子组件实例,并调用子组件的方法。例如:
```vue
<template>
<div>
<ChildComponent ref="childRef" />
<button @click="handleClick">调用子组件方法</button>
</div>
</template>
<script>
import { onMounted, getCurrentInstance } from 'vue'
export default {
setup() {
const childRef = getCurrentInstance().refs.childRef
const handleClick = () => {
childRef.childMethod.value()
}
onMounted(() => {
console.log(childRef) // 打印子组件实例
})
return {
handleClick
}
}
}
</script>
```
阅读全文
相关推荐














