vue实现电影选择
Vue 实现电影选择功能
创建 Vue 项目
使用 Vue CLI 创建一个新项目,确保已安装 Vue CLI。运行以下命令创建项目:
vue create movie-selection
cd movie-selection
安装依赖
如果需要使用 Axios 进行数据请求,安装 Axios:
npm install axios
创建电影列表组件
在 src/components 目录下创建 MovieList.vue 文件,用于显示电影列表和选择功能。
<template>
<div>
<h3>电影列表</h3>
<ul>
<li v-for="movie in movies" :key="movie.id" @click="selectMovie(movie)">
{{ movie.title }} - {{ movie.year }}
</li>
</ul>
<div v-if="selectedMovie">
<h3>已选择: {{ selectedMovie.title }}</h3>
<p>年份: {{ selectedMovie.year }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
movies: [
{ id: 1, title: '肖申克的救赎', year: 1994 },
{ id: 2, title: '阿甘正传', year: 1994 },
{ id: 3, title: '泰坦尼克号', year: 1997 }
],
selectedMovie: null
}
},
methods: {
selectMovie(movie) {
this.selectedMovie = movie
}
}
}
</script>
动态加载电影数据
如果需要从 API 动态加载电影数据,可以使用 Axios:
<script>
import axios from 'axios'
export default {
data() {
return {
movies: [],
selectedMovie: null
}
},
created() {
this.fetchMovies()
},
methods: {
fetchMovies() {
axios.get('https://api.example.com/movies')
.then(response => {
this.movies = response.data
})
.catch(error => {
console.error('获取电影数据失败:', error)
})
},
selectMovie(movie) {
this.selectedMovie = movie
}
}
}
</script>
添加样式
为电影列表和选择项添加基本样式:
<style scoped>
ul {
list-style-type: none;
padding: 0;
}
li {
padding: 8px;
margin: 5px 0;
background-color: #f0f0f0;
cursor: pointer;
}
li:hover {
background-color: #e0e0e0;
}
</style>
在主应用中使用组件
在 src/App.vue 中引入并使用 MovieList 组件:
<template>
<div id="app">
<MovieList />
</div>
</template>
<script>
import MovieList from './components/MovieList.vue'
export default {
name: 'App',
components: {
MovieList
}
}
</script>
运行项目
启动开发服务器查看效果:

npm run serve
扩展功能
- 添加搜索功能,允许用户搜索特定电影
- 实现多选功能,允许用户选择多部电影
- 添加电影详情页面,显示更多信息
- 使用 Vuex 管理电影选择和状态
这个实现提供了基本的电影选择功能,可以根据需求进一步扩展和完善。






