vue 子组件用父组件方法
时间: 2023-08-21 22:06:16 浏览: 46
要在子组件中使用父组件的方法,可以通过使用 `$emit` 方法将子组件的事件传递给父组件,然后在父组件中定义该事件的处理方法。
以下是一个示例代码:
在父组件中:
```vue
<template>
<div>
<child-component @childEvent="handleChildEvent"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleChildEvent(data) {
// 在父组件中处理子组件的事件
console.log("父组件接收到子组件的事件,数据为:", data);
// 执行父组件的方法
this.parentMethod();
},
parentMethod() {
console.log("这是父组件的方法");
}
}
};
</script>
```
在子组件中:
```vue
<template>
<div>
<button @click="triggerEvent">触发事件</button>
</div>
</template>
<script>
export default {
methods: {
triggerEvent() {
// 在子组件中触发事件,并将数据传递给父组件
this.$emit("childEvent", "这是子组件的数据");
}
}
};
</script>
`