vue3 子组件调子组件方法
时间: 2023-06-22 18:19:40 浏览: 61
在 Vue3 中,你可以通过 `ref` 和 `value` 来获取子组件实例并调用它的方法。
首先,在子组件中,你需要在 `setup` 函数中使用 `ref` 来创建一个指向子组件实例的引用:
```
<template>
<div>子组件</div>
</template>
<script>
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const childInstance = ref(null)
const callChildMethod = () => {
childInstance.value.childMethod()
}
return {
childInstance,
callChildMethod
}
},
methods: {
childMethod() {
console.log('子组件的方法被调用了!')
}
}
})
</script>
```
然后,在父组件中,你可以使用 `ref` 来获取子组件实例的引用,并调用子组件的方法:
```
<template>
<div>
<ChildComponent ref="childRef" />
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
import { defineComponent, ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
export default defineComponent({
components: {
ChildComponent
},
setup() {
const childRef = ref(null)
const callChildMethod = () => {
childRef.value.callChildMethod()
}
return {
childRef,
callChildMethod
}
}
})
</script>
```
需要注意的是,如果你想调用的子组件方法是异步的,你需要使用 `$nextTick` 来确保子组件已经完全渲染完毕后再调用方法。例如:
```
const callChildMethod = () => {
this.$nextTick(() => {
childRef.value.callChildMethod()
})
}
```