vue实现影片列表
Vue 实现影片列表
使用 Vue CLI 创建项目
确保已安装 Vue CLI,通过以下命令创建新项目:
vue create movie-list
cd movie-list
安装依赖
根据需要安装 axios 用于数据请求:

npm install axios
创建影片列表组件
在 src/components 目录下创建 MovieList.vue 文件:
<template>
<div class="movie-list">
<h2>影片列表</h2>
<ul>
<li v-for="movie in movies" :key="movie.id">
{{ movie.title }} - {{ movie.year }}
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
movies: []
};
},
async created() {
try {
const response = await axios.get('https://api.example.com/movies');
this.movies = response.data;
} catch (error) {
console.error('获取影片列表失败:', error);
}
}
};
</script>
<style scoped>
.movie-list {
max-width: 600px;
margin: 0 auto;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 8px;
border-bottom: 1px solid #eee;
}
</style>
在主组件中引入
修改 src/App.vue 文件以使用 MovieList 组件:

<template>
<div id="app">
<MovieList />
</div>
</template>
<script>
import MovieList from './components/MovieList.vue';
export default {
components: {
MovieList
}
};
</script>
运行项目
启动开发服务器:
npm run serve
可选优化
- 分页加载:通过 API 分页参数实现懒加载。
- 搜索功能:添加输入框绑定搜索事件过滤列表。
- 状态管理:对于复杂场景,可使用 Vuex 管理影片数据。
示例 API 数据格式
假设后端返回的影片数据格式如下:
[
{ "id": 1, "title": "影片A", "year": 2020 },
{ "id": 2, "title": "影片B", "year": 2021 }
]






