如何不使用v-on指令从子组件emit事件中获取值?
Hey there! Let's break down how to capture that init-event value from the Child component without using v-on in the Parent's template. Here are two reliable approaches depending on your Vue version and use case:
Approach 1: Use $refs to manually bind the event listener (Recommended)
This is the cleanest and most explicit method—you'll reference the Child component directly and attach the event listener programmatically.
First, add a ref attribute to the Child component in the Parent's template:
<template> <!-- Give the Child component a ref to access its instance --> <Child ref="targetChild" /> </template>
Then, in the Parent's script section, use the ref to get the Child instance and listen for the init-event:
// Vue 2 Options API export default { data() { return { capturedValue: null }; }, methods: { getChildEventValue() { // Grab the Child component instance from $refs const childInstance = this.$refs.targetChild; if (childInstance) { // Attach the event listener to catch 'init-event' childInstance.$on('init-event', (value) => { console.log("Received value from Child:", value); // Logs 100 this.capturedValue = value; // Store the value in Parent's data }); } } }, mounted() { // Call the method when the Parent mounts (adjust timing based on your needs) this.getChildEventValue(); } };
For Vue 3 Composition API (with <script setup>), the syntax is slightly adjusted but follows the same logic:
<template> <Child ref="targetChild" /> </template> <script setup> import { ref, onMounted } from 'vue'; import Child from './Child.vue'; const targetChild = ref(null); const capturedValue = ref(null); const getChildEventValue = () => { if (targetChild.value) { targetChild.value.$on('init-event', (value) => { capturedValue.value = value; console.log("Received value:", value); }); } }; onMounted(() => { getChildEventValue(); }); </script>
Pro Tip: Make sure you bind the listener before the Child component triggers someMethod()—otherwise you'll miss the event. If someMethod() runs on Child's mount, calling getChildEventValue() in Parent's mounted hook works perfectly (since Parent's mounted runs after all Child components have mounted).
Approach 2: Use $children (Not Recommended)
You could also search for the Child component instance via $children, but this approach is fragile because $children returns components in the order they're rendered—this can break if you add/remove sibling components later.
Here's how it would look (for Vue 2):
export default { methods: { getChildEventValue() { // Find the Child component by its name (adjust if your component has a different name) const childInstance = this.$children.find(child => child.$options.name === 'Child'); if (childInstance) { childInstance.$on('init-event', (value) => { console.log("Captured value:", value); }); } } }, mounted() { this.getChildEventValue(); } };
Stick with $refs unless you have a specific reason to use this!
内容的提问来源于stack exchange,提问作者StockholmSyndrom

