vue2子组件调用父组件的方法
时间: 2024-09-05 14:02:54 浏览: 74
在 Vue 2 中,子组件想要调用父组件的方法,可以使用 this.$parent
或者 $emit
来实现。这是通过事件系统完成的:
通过 $parent: 子组件可以在需要的时候直接引用
this.$parent
,然后访问父组件暴露的方法。例如,在子组件的模板里:<button @click="callParentMethod">调用父方法</button> <script> export default { methods: { callParentMethod() { this.$parent.parentMethod(); } } } </script>
这样,当按钮被点击时,会执行
parentMethod
。通过 $emit (事件发射): 如果你想让父组件主动触发某个行为,通常会通过
v-on
或者@
指令绑定到parent-method
的事件上。在子组件里先发出事件:<button @click="emitEvent">调用父方法</button> <script> export default { methods: { emitEvent() { this.$emit('parent-method'); } } } </script>
然后在父组件的模板里接收这个事件并处理:
<template> <div> <child-component @parent-method="handleParentMethod"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { handleParentMethod() { // 处理父组件接收到的方法调用 } } } </script>
相关推荐


















