vue实现电影排行
实现电影排行的Vue组件
使用Vue实现电影排行功能可以通过以下步骤完成。假设使用Vue 3和Composition API。
数据准备
创建一个电影数据数组,包含电影名称、评分和封面图等信息:
const movies = [
{ id: 1, title: '肖申克的救赎', rating: 9.7, cover: 'url1' },
{ id: 2, title: '教父', rating: 9.6, cover: 'url2' },
{ id: 3, title: '黑暗骑士', rating: 9.5, cover: 'url3' }
]
组件结构
创建电影排行组件的基本结构:

<template>
<div class="movie-ranking">
<h3>电影排行榜</h3>
<div class="ranking-list">
<div
v-for="(movie, index) in sortedMovies"
:key="movie.id"
class="movie-item"
>
<span class="rank">{{ index + 1 }}</span>
<img :src="movie.cover" :alt="movie.title">
<div class="movie-info">
<h4>{{ movie.title }}</h4>
<div class="rating">
<span>评分: {{ movie.rating }}</span>
</div>
</div>
</div>
</div>
</div>
</template>
排序逻辑
在script部分实现按评分排序的逻辑:
import { ref, computed } from 'vue'
export default {
setup() {
const movies = ref([
// 电影数据
])
const sortedMovies = computed(() => {
return [...movies.value].sort((a, b) => b.rating - a.rating)
})
return { sortedMovies }
}
}
样式设计
添加基本CSS样式美化排行列表:

.movie-ranking {
max-width: 800px;
margin: 0 auto;
}
.ranking-list {
display: flex;
flex-direction: column;
gap: 15px;
}
.movie-item {
display: flex;
align-items: center;
background: #f5f5f5;
padding: 10px;
border-radius: 8px;
}
.rank {
font-size: 24px;
font-weight: bold;
margin-right: 20px;
color: #ff9800;
}
.movie-item img {
width: 80px;
height: 120px;
object-fit: cover;
margin-right: 20px;
}
.movie-info {
flex: 1;
}
.rating {
color: #ff9800;
font-weight: bold;
}
动态数据获取
如果需要从API获取数据,可以使用axios:
import { ref, onMounted } from 'vue'
import axios from 'axios'
export default {
setup() {
const movies = ref([])
const fetchMovies = async () => {
try {
const response = await axios.get('API_URL')
movies.value = response.data
} catch (error) {
console.error('获取电影数据失败:', error)
}
}
onMounted(fetchMovies)
return { movies }
}
}
添加交互功能
可以增加点击事件查看电影详情:
<div
v-for="(movie, index) in sortedMovies"
:key="movie.id"
class="movie-item"
@click="showDetail(movie)"
>
const showDetail = (movie) => {
// 跳转到详情页或显示模态框
console.log('查看电影:', movie.title)
}
响应式设计
添加媒体查询确保在不同设备上显示良好:
@media (max-width: 600px) {
.movie-item {
flex-direction: column;
text-align: center;
}
.rank {
margin-right: 0;
margin-bottom: 10px;
}
.movie-item img {
margin-right: 0;
margin-bottom: 10px;
}
}
以上实现包含了电影排行的核心功能,可以根据实际需求进一步扩展,如添加分页、筛选、搜索等功能。






