vue2父组件调用子组件的方法
时间: 2023-11-29 07:46:59 浏览: 36
在Vue2中,父组件可以通过以下两种方式调用子组件的方法:
1. 通过事件监听器
在子组件中,可以通过$emit方法触发一个自定义事件,并将需要传递的参数作为$emit方法的第二个参数传入。在父组件中,可以通过在子组件上使用v-on指令监听这个自定义事件,并在回调函数中调用需要调用的子组件方法。具体实现如下:
引用:
父组件
```html
<template>
<div>
<child @fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('测试');
}
}
};
</script>
```
子组件
```html
<template>
<div>
<button @click="handleClick">调用父组件方法</button>
</div>
</template>
<script>
export default {
methods: {
handleClick() {
this.$emit('fatherMethod');
}
}
};
</script>
```
2. 通过props
在父组件中,可以通过在子组件上使用v-bind指令将父组件的方法作为props传递给子组件。在子组件中,可以通过this.$props访问到这个方法,并在需要的时候调用它。具体实现如下:
引用:
父组件
```html
<template>
<div>
<child :fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('测试');
}
}
};
</script>
```
子组件
```html
<template>
<div>
<button @click="handleClick">调用父组件方法</button>
</div>
</template>
<script>
export default {
props: {
fatherMethod: {
type: Function,
required: true
}
},
methods: {
handleClick() {
this.$props.fatherMethod();
}
}
};
</script>
```