vue中父级如何向子集触发函数
时间: 2024-01-26 17:05:07 浏览: 26
在 Vue 中,父组件向子组件触发函数可以通过以下步骤实现:
1. 在父组件中定义一个函数,并将该函数通过 props 属性传递给子组件。
2. 在子组件中,使用 $emit 方法触发父组件传递的函数。
具体的实现步骤如下:
父组件:
```vue
<template>
<div>
<button @click="handleClick">触发子组件函数</button>
<Child :callFunc="callChildFunc" />
</div>
</template>
<script>
import Child from './Child.vue';
export default {
components: {
Child,
},
methods: {
handleClick() {
this.$refs.child.callParentFunc();
},
callChildFunc() {
console.log('父组件调用了子组件的函数');
},
},
};
</script>
```
在父组件中,我们定义了一个 handleClick 函数,并将该函数通过 props 属性传递给子组件 Child。同时,在父组件中还定义了一个名为 callChildFunc 的函数,用于在子组件中被调用。
子组件:
```vue
<template>
<div>
<button @click="callParentFunc">触发父组件函数</button>
</div>
</template>
<script>
export default {
props: {
callFunc: Function,
},
methods: {
callParentFunc() {
this.callFunc();
},
},
};
</script>
```
在子组件中,我们接收了父组件传递过来的 callFunc 函数,并在 callParentFunc 函数中使用 $emit 方法触发该函数,从而让父组件调用该函数。
需要注意的是,在父组件中使用子组件的 callParentFunc 函数需要使用 $refs 以获取子组件的实例。