Vue三层组件Emit异常:Carousel无法向上传递事件
Let's break down why your Home component isn't receiving the setMovie event from Carousel, and fix it step by step.
The Root Problem
In your Carousel component's template, when you listen to the setMovie event from MovieCard, you're trying to pass movieKey to your $emit call—but this variable doesn't exist in the Carousel component's context. That means you're either emitting an undefined value, or Vue is throwing a silent error that breaks the event chain entirely.
The Fix
You need to properly capture the value that MovieCard emits and forward it to Home. There are two clean ways to do this:
Option 1: Use $event in the Template
Vue automatically passes the emitted value to the $event variable (for single-parameter events). Update your Carousel template to use this variable when re-emitting the event:
<div class="carousel-item active"> <div class="row ml-1"> <h1>{{selectedMovie}}</h1> <MovieCard v-for="m in movies" :key="m.MovieKey" @setMovie="$emit('setMovie', $event)" /> </div> </div>
Option 2: Use a Method for Clarity (Recommended)
If you prefer more readable code (especially if you might add logic later), create a method in Carousel to handle the event and re-emit it:
First, add the method to your Carousel component's methods object:
methods: { forwardSetMovie(movieKey) { this.$emit('setMovie', movieKey); } }
Then update the template to call this method instead:
<div class="carousel-item active"> <div class="row ml-1"> <h1>{{selectedMovie}}</h1> <MovieCard v-for="m in movies" :key="m.MovieKey" @setMovie="forwardSetMovie" /> </div> </div>
Why This Works
- Your
MovieCardcomponent is correctly emitting themovieKeyvalue when clicked. - The
Carouselcomponent now properly captures that value (either via$eventor the method parameter) and forwards it to theHomecomponent using$emit('setMovie', ...). - Your
Homecomponent'stestmethod will now trigger as expected when aMovieCardis clicked.
Quick Check
Double-check that your MovieCard component has access to the movieKey variable you're emitting. It should be defined as a prop, like this:
<script> export default { props: ['movieKey'] } </script>
This ensures the value being emitted from MovieCard is the correct one passed down from Carousel via the loop.
内容的提问来源于stack exchange,提问作者Kevin Bryan

