在 Vue 2 中,$listeners 主要用于传递父组件的事件监听器到子组件,以便子组件可以监听和处理这些事件。
Tips:当父组件需要将自定义事件传递给子组件时,可以直接使用
v-on="$listeners"将父组件上的事件监听器传递给子组件。在子组件内部,可以通过this.$emit(eventName)的方式来触发该事件。
示例一:父子组件之间的值传递
在这个例子中,Parent 向 Child 传递了一个 customEvent 事件,并在父组件中定义了处理该事件的方法 handleCustomEvent。Child 中的按钮被点击时,通过 $emit 触发了 customEvent 事件,并携带了一个值。父组件监听 customEvent 事件并在 handleCustomEvent 方法中处理事件和值。通过这种方式实现了在 Vue 2 中使用 $listeners 进行事件传递和值传递的操作。
- 父组件:Parent.vue
<template>
<Child v-on:customEvent="handleCustomEvent" />
</template>
<script>
import Child from './Child.vue';
export default {
components: { Child },
methods: {
handleCustomEvent(value) {
console.log('Received value in parent component:', value);
}
}
};
</script>
- 子组件:Child.vue
<template>
<button @click="$emit('customEvent', 'I am child!')">Trigger Custom Event</button>
</template>
示例二:祖孙组件之间的的值传递
在这个示例中,Grandparent 作为祖父组件,通过监听 Parent 的 customEvent 事件来传递值。Parent 作为父组件,接收到该事件后再通过 $emit 触发自己的 customEvent 事件,并将值传递给 Grandparent。Child 作为子组件,通过点击按钮触发自己的 customEvent 事件,并将值传递给 Parent,而 Parent 继续触发 customEvent 事件最终将值传递给 Child。
<!-- Grandparent.vue -->
<template>
<Parent v-on:customEvent="handleCustomEvent" />
</template>
<script>
import Parent from './Parent.vue';
export default {
components: { Parent },
methods: {
handleCustomEvent(value) {
console.log('Received value in grandparent component:', value);
}
}
};
</script>
<!-- Parent.vue -->
<template>
<Child v-on:customEvent="handleCustomEvent" />
</template>
<script>
import Child from './Child.vue';
export default {
components: { Child },
methods: {
handleCustomEvent(value) {
console.log('Received value in parent component:', value);
this.$emit('customEvent', value); // 触发自定义事件
}
}
};
</script>
<!-- Child.vue -->
<template>
<button @click="$emit('customEvent', 'I am child!')">Trigger Custom Event</button>
</template>