vue2中子组件调用父组件的方法
时间: 2023-11-25 13:07:09 浏览: 34
在Vue2中,子组件可以通过props属性接收父组件传递的方法,然后在子组件中调用该方法。具体步骤如下:
1.在父组件中定义一个方法,例如fatherMethod。
2.在父组件中引入子组件,并将该方法通过props属性传递给子组件,例如:fatherMethod="fatherMethod"。
3.在子组件中通过props属性接收该方法,并在需要的地方调用该方法,例如:this.$props.fatherMethod()。
下面是一个示例代码:
父组件:
```html
<template>
<div>
<child :fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from './components/childcomponent';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('父组件方法');
}
}
};
</script>
```
子组件:
```html
<template>
<div>
<button @click="callFatherMethod">调用父组件方法</button>
</div>
</template>
<script>
export default {
props: {
fatherMethod: {
type: Function,
required: true
}
},
methods: {
callFatherMethod() {
this.$props.fatherMethod();
}
}
};
</script>
```