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 (err) {
this.error = err.message;
} finally {
this.loading = false;
}
}
},
created() {
this.fetchMovies();
}
电影列表渲染
使用 v-for 指令遍历电影数据,动态生成电影卡片。每张卡片包含电影海报、标题、评分等信息。
<template>
<div class="movie-list">
<div v-if="loading">Loading...</div>
<div v-else-if="error">{{ error }}</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>Rating: {{ movie.vote_average }}</p>
</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,并请求详细数据。
const router = new VueRouter({
routes: [
{ path: '/movie/:id', component: MovieDetail }
]
});
分页功能
在数据请求中添加分页参数,使用分页组件控制当前页码。更新页码时重新获取数据。

methods: {
async fetchMovies(page = 1) {
const response = await axios.get(`https://api.themoviedb.org/3/movie/popular?api_key=YOUR_API_KEY&page=${page}`);
this.movies = response.data.results;
}
}
样式与布局
使用 CSS 或 UI 框架(如 Vuetify、Element UI)美化电影列表和详情页。确保响应式设计,适配不同屏幕尺寸。
.movie-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
}
.movie-card {
border: 1px solid #ddd;
padding: 10px;
border-radius: 5px;
}
状态管理
对于复杂应用,使用 Vuex 管理电影数据、搜索状态和分页信息。通过 actions 发起异步请求,mutations 更新状态。
const store = new Vuex.Store({
state: {
movies: [],
searchQuery: ''
},
mutations: {
SET_MOVIES(state, movies) {
state.movies = movies;
}
},
actions: {
async fetchMovies({ commit }, page) {
const response = await axios.get(`https://api.themoviedb.org/3/movie/popular?api_key=YOUR_API_KEY&page=${page}`);
commit('SET_MOVIES', response.data.results);
}
}
});





