VUE3.2 父组件怎么调用子组件的方法
时间: 2023-06-22 19:30:57 浏览: 58
在 Vue 3.2 中,您可以通过 `ref` 和 `defineExpose` 来访问子组件的方法。
首先,在子组件中,您需要使用 `defineExpose` 函数来暴露需要向父组件公开的方法。例如:
```vue
<template>
<div>{{ count }}</div>
</template>
<script>
import { defineComponent } from 'vue'
export default defineComponent({
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
},
decrement() {
this.count--
},
reset() {
this.count = 0
},
// 使用 defineExpose 函数暴露 increment 方法
// 注意,只有被暴露的属性和方法才能被父组件访问
defineExpose() {
return {
increment: this.increment
}
}
}
})
</script>
```
在上面的示例中,我们使用 `defineExpose` 函数暴露了 `increment` 方法,该方法会增加 `count` 属性的值。
然后,在父组件中,您可以使用 `ref` 来获取子组件实例,并通过该实例来调用子组件的方法。例如:
```vue
<template>
<div>
<button @click="handleClick">调用子组件的 increment 方法</button>
</div>
<child-component ref="child"></child-component>
</template>
<script>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
setup() {
const childRef = ref(null)
const handleClick = () => {
childRef.value.increment()
}
return {
childRef,
handleClick
}
}
}
</script>
```
在上面的示例中,我们首先使用 `ref` 函数创建了一个子组件的引用 `childRef`,并在父组件的 `setup` 函数中定义了一个 `handleClick` 函数,该函数通过 `childRef.value` 获取子组件实例,并调用子组件暴露的 `increment` 方法来增加 `count` 属性的值。在模板中,我们使用 `handleClick` 来调用子组件的 `increment` 方法。
注意,只有在子组件中使用 `defineExpose` 函数暴露的属性和方法才能被父组件访问。如果子组件中没有使用 `defineExpose` 函数来暴露方法,父组件将无法访问子组件的方法。同时,`defineExpose` 函数返回的对象中,只有被暴露的属性和方法才能被父组件访问,未被暴露的属性和方法将不会被父组件访问到。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)