vue3 父组件调用子组件函数
时间: 2023-10-19 09:30:47 浏览: 107
在 Vue 3 中,可以通过使用 `ref` 或 `provide/inject` 来实现父组件调用子组件的函数。
1. 使用 `ref`:
在子组件中,将需要被父组件调用的函数定义为 `ref` 变量,并通过 `toRef` 将其转换为一个只读引用。然后,将该引用传递给父组件,以便父组件可以调用子组件的函数。
子组件代码示例:
```vue
<template>
<div>
<button @click="handleClick">子组件按钮</button>
</div>
</template>
<script>
import { ref, toRef } from 'vue';
export default {
setup() {
const handleClick = () => {
console.log('子组件函数被调用');
};
return {
handleClick: toRef(window, handleClick), // 将函数转换为只读引用
};
},
};
</script>
```
父组件调用子组件函数的示例:
```vue
<template>
<div>
<ChildComponent :handleClick="handleChildClick" />
<button @click="handleParentClick">父组件按钮</button>
</div>
</template>
<script>
import ChildComponent from '@/components/ChildComponent.vue';
export default {
components: {
ChildComponent,
},
methods: {
handleChildClick() {
this.$refs.child.handleClick(); // 通过子组件的引用调用子组件函数
},
handleParentClick() {
this.handleChildClick(); // 调用子组件函数
},
},
};
</script>
```
2. 使用 `provide/inject`:
在子组件中,使用 `provide` 提供一个函数,然后在父组件中使用 `inject` 获取该函数,并直接调用子组件的函数。
子组件代码示例:
```vue
<template>
<div>
<button @click="handleClick">子组件按钮</button>
</div>
</template>
<script>
import { provide } from 'vue';
export default {
setup() {
const handleClick = () => {
console.log('子组件函数被调用');
};
provide('handleClick', handleClick); // 提供函数给父组件
return {
handleClick,
};
},
};
</script>
```
父组件调用子组件函数的示例:
```vue
<template>
<div>
<ChildComponent />
<button @click="handleClick">父组件按钮</button>
</div>
</template>
<script>
import { inject } from 'vue';
export default {
components: {
ChildComponent,
},
setup() {
const handleClick = inject('handleClick'); // 获取子组件提供的函数
const handleParentClick = () => {
handleClick(); // 直接调用子组件函数
};
return {
handleParentClick,
};
},
};
</script>
```
以上是两种在 Vue 3 中实现父组件调用子组件函数的方法。具体选择哪种方式取决于你的需求和组件架构。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)