vue电影功能实现
Vue 电影功能实现
电影列表展示
使用 Vue 的 v-for 指令动态渲染电影列表。通过 API 获取电影数据,存储在组件的 data 属性中。
<template>
<div class="movie-list">
<div v-for="movie in movies" :key="movie.id" class="movie-item">
<img :src="movie.poster" :alt="movie.title">
<h3>{{ movie.title }}</h3>
<p>{{ movie.year }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
movies: []
}
},
created() {
fetch('https://api.example.com/movies')
.then(response => response.json())
.then(data => {
this.movies = data;
});
}
}
</script>
电影搜索功能
添加搜索输入框,使用 v-model 绑定搜索关键词,通过计算属性过滤电影列表。

<template>
<input v-model="searchQuery" placeholder="Search movies...">
<div v-for="movie in filteredMovies" :key="movie.id">
{{ movie.title }}
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
movies: []
}
},
computed: {
filteredMovies() {
return this.movies.filter(movie =>
movie.title.toLowerCase().includes(this.searchQuery.toLowerCase())
);
}
}
}
</script>
电影详情页
使用 Vue Router 实现电影详情页的导航。通过动态路由参数获取电影 ID,并显示详细信息。

// router.js
const routes = [
{ path: '/movie/:id', component: MovieDetail }
];
// MovieDetail.vue
<template>
<div v-if="movie">
<h1>{{ movie.title }}</h1>
<p>{{ movie.plot }}</p>
</div>
</template>
<script>
export default {
data() {
return {
movie: null
}
},
created() {
const movieId = this.$route.params.id;
fetch(`https://api.example.com/movies/${movieId}`)
.then(response => response.json())
.then(data => {
this.movie = data;
});
}
}
</script>
电影评分功能
实现星级评分组件,使用自定义事件将评分数据传递给父组件。
<template>
<div class="star-rating">
<span
v-for="star in 5"
:key="star"
@click="rate(star)"
:class="{ 'active': star <= currentRating }"
>★</span>
</div>
</template>
<script>
export default {
data() {
return {
currentRating: 0
}
},
methods: {
rate(star) {
this.currentRating = star;
this.$emit('rated', star);
}
}
}
</script>
电影收藏功能
使用 Vuex 管理全局状态,实现电影收藏功能。通过 mutations 修改收藏状态。
// store.js
const store = new Vuex.Store({
state: {
favorites: []
},
mutations: {
toggleFavorite(state, movie) {
const index = state.favorites.findIndex(fav => fav.id === movie.id);
if (index === -1) {
state.favorites.push(movie);
} else {
state.favorites.splice(index, 1);
}
}
}
});
// MovieItem.vue
<template>
<button @click="toggleFavorite(movie)">
{{ isFavorite ? 'Remove from favorites' : 'Add to favorites' }}
</button>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
props: ['movie'],
computed: {
...mapState(['favorites']),
isFavorite() {
return this.favorites.some(fav => fav.id === this.movie.id);
}
},
methods: {
...mapMutations(['toggleFavorite'])
}
}
</script>






