vue电影功能实现
Vue电影功能实现
数据获取与展示
使用Axios或Fetch API从电影API获取数据,例如TMDB或豆瓣API。在Vue组件的created或mounted生命周期钩子中发起请求,将返回的电影数据存储在组件的data属性中。
data() {
return {
movies: [],
loading: false,
error: null
}
},
methods: {
async fetchMovies() {
this.loading = true;
try {
const response = await axios.get('https://api.themoviedb.org/3/movie/popular?api_key=YOUR_API_KEY');
this.movies = response.data.results;
} catch (error) {
this.error = error;
} finally {
this.loading = false;
}
}
},
mounted() {
this.fetchMovies();
}
电影列表渲染
使用Vue的v-for指令遍历电影数据,动态生成电影卡片。每张卡片包含电影海报、标题、评分和简介等信息。

<template>
<div class="movie-list">
<div v-if="loading">Loading...</div>
<div v-else-if="error">{{ error.message }}</div>
<div v-else>
<div v-for="movie in movies" :key="movie.id" class="movie-card">
<img :src="`https://image.tmdb.org/t/p/w500${movie.poster_path}`" :alt="movie.title">
<h3>{{ movie.title }}</h3>
<p>{{ movie.overview }}</p>
<span>Rating: {{ movie.vote_average }}</span>
</div>
</div>
</div>
</template>
搜索功能实现
添加搜索输入框,使用v-model绑定搜索关键词。通过计算属性或方法过滤电影列表,实现实时搜索功能。
data() {
return {
searchQuery: ''
}
},
computed: {
filteredMovies() {
return this.movies.filter(movie =>
movie.title.toLowerCase().includes(this.searchQuery.toLowerCase())
);
}
}
电影详情页
使用Vue Router配置动态路由,点击电影卡片跳转到详情页。详情页根据电影ID从API获取详细信息并展示。

const router = new VueRouter({
routes: [
{ path: '/movie/:id', component: MovieDetail }
]
});
<template>
<div class="movie-detail">
<h1>{{ movie.title }}</h1>
<img :src="`https://image.tmdb.org/t/p/w500${movie.poster_path}`" :alt="movie.title">
<p>{{ movie.overview }}</p>
<p>Release Date: {{ movie.release_date }}</p>
<p>Rating: {{ movie.vote_average }}</p>
</div>
</template>
分页功能
在获取电影数据时添加分页参数,使用分页组件控制当前页码。每次页码变化时重新获取对应页的电影数据。
data() {
return {
currentPage: 1,
totalPages: 0
}
},
methods: {
async fetchMovies() {
const response = await axios.get(`https://api.themoviedb.org/3/movie/popular?api_key=YOUR_API_KEY&page=${this.currentPage}`);
this.movies = response.data.results;
this.totalPages = response.data.total_pages;
},
changePage(page) {
this.currentPage = page;
this.fetchMovies();
}
}
样式与布局
使用CSS或UI框架(如Vuetify、Element UI)美化电影列表和详情页。确保布局响应式,适配不同屏幕尺寸。
.movie-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
}
.movie-card {
border: 1px solid #ddd;
padding: 10px;
border-radius: 5px;
}
.movie-card img {
width: 100%;
height: auto;
}






