vue实现电影排行表
Vue 实现电影排行表
数据准备
使用 Vue 实现电影排行表需要准备电影数据,通常以数组形式存储,包含电影名称、评分、上映年份等信息。例如:
data() {
return {
movies: [
{ name: '电影A', rating: 9.2, year: 2020 },
{ name: '电影B', rating: 8.7, year: 2019 },
{ name: '电影C', rating: 8.5, year: 2021 }
]
}
}
表格渲染
使用 Vue 的模板语法 v-for 动态渲染电影数据到表格中。在模板中添加表格结构:
<table>
<thead>
<tr>
<th>排名</th>
<th>电影名称</th>
<th>评分</th>
<th>上映年份</th>
</tr>
</thead>
<tbody>
<tr v-for="(movie, index) in movies" :key="index">
<td>{{ index + 1 }}</td>
<td>{{ movie.name }}</td>
<td>{{ movie.rating }}</td>
<td>{{ movie.year }}</td>
</tr>
</tbody>
</table>
排序功能
实现按评分或年份排序的功能,可以通过计算属性或方法对数据进行排序。例如,添加一个计算属性来返回排序后的电影列表:

computed: {
sortedMovies() {
return [...this.movies].sort((a, b) => b.rating - a.rating);
}
}
在模板中使用 sortedMovies 替代原始的 movies 数据:
<tr v-for="(movie, index) in sortedMovies" :key="index">
<td>{{ index + 1 }}</td>
<td>{{ movie.name }}</td>
<td>{{ movie.rating }}</td>
<td>{{ movie.year }}</td>
</tr>
样式优化
为表格添加 CSS 样式,使其更美观。例如:

table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
动态交互
添加交互功能,如点击表头切换排序方式。通过添加点击事件和方法来实现:
methods: {
sortByRating() {
this.movies.sort((a, b) => b.rating - a.rating);
},
sortByYear() {
this.movies.sort((a, b) => b.year - a.year);
}
}
在表头中绑定点击事件:
<th @click="sortByRating">评分</th>
<th @click="sortByYear">上映年份</th>
完整示例
以下是一个完整的 Vue 单文件组件示例:
<template>
<div>
<table>
<thead>
<tr>
<th>排名</th>
<th>电影名称</th>
<th @click="sortByRating">评分</th>
<th @click="sortByYear">上映年份</th>
</tr>
</thead>
<tbody>
<tr v-for="(movie, index) in movies" :key="index">
<td>{{ index + 1 }}</td>
<td>{{ movie.name }}</td>
<td>{{ movie.rating }}</td>
<td>{{ movie.year }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
movies: [
{ name: '电影A', rating: 9.2, year: 2020 },
{ name: '电影B', rating: 8.7, year: 2019 },
{ name: '电影C', rating: 8.5, year: 2021 }
]
}
},
methods: {
sortByRating() {
this.movies.sort((a, b) => b.rating - a.rating);
},
sortByYear() {
this.movies.sort((a, b) => b.year - a.year);
}
}
}
</script>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
cursor: pointer;
}
</style>
通过以上步骤,可以实现一个功能完整且美观的电影排行表。






