vue实现视频列表
Vue 实现视频列表
在 Vue 中实现视频列表通常需要结合数据绑定、组件化和第三方库(如视频播放器)。以下是具体实现方法:
数据准备
创建一个数组存储视频信息,包括标题、封面图、视频链接等:
data() {
return {
videos: [
{
id: 1,
title: '视频1',
cover: 'https://example.com/cover1.jpg',
url: 'https://example.com/video1.mp4'
},
{
id: 2,
title: '视频2',
cover: 'https://example.com/cover2.jpg',
url: 'https://example.com/video2.mp4'
}
]
}
}
列表渲染
使用 v-for 指令渲染视频列表:
<div class="video-list">
<div
v-for="video in videos"
:key="video.id"
class="video-item"
>
<img :src="video.cover" :alt="video.title">
<h3>{{ video.title }}</h3>
<video controls>
<source :src="video.url" type="video/mp4">
</video>
</div>
</div>
样式优化
添加基础样式使列表更美观:
.video-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 20px;
}
.video-item {
border: 1px solid #eee;
padding: 10px;
border-radius: 8px;
}
.video-item video {
width: 100%;
margin-top: 10px;
}
使用视频播放器库
对于更复杂的播放需求,可以集成第三方库如 vue-video-player:
npm install vue-video-player video.js
组件中使用:
import { videoPlayer } from 'vue-video-player'
import 'video.js/dist/video-js.css'
export default {
components: {
videoPlayer
}
}
模板部分:
<video-player
v-for="video in videos"
:key="video.id"
:options="{
sources: [{
src: video.url,
type: 'video/mp4'
}],
poster: video.cover
}"
/>
懒加载优化
对于长列表,建议实现懒加载:
methods: {
handleScroll() {
const bottom = window.innerHeight + window.scrollY >= document.body.offsetHeight
if (bottom) {
// 加载更多视频
}
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
响应式布局
根据屏幕尺寸调整列数:
computed: {
gridColumns() {
return window.innerWidth < 600 ? 1 :
window.innerWidth < 900 ? 2 : 3
}
}






