vue实现视频列表代码
以下是一个基于Vue.js的视频列表实现示例,包含关键功能代码和说明:
视频列表基础实现
<template>
<div class="video-list">
<div v-for="video in videos" :key="video.id" class="video-item">
<video controls width="250">
<source :src="video.url" :type="video.type">
</video>
<h3>{{ video.title }}</h3>
<p>{{ video.description }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
videos: [
{
id: 1,
title: '示例视频1',
description: '这是第一个示例视频',
url: 'https://example.com/video1.mp4',
type: 'video/mp4'
},
{
id: 2,
title: '示例视频2',
description: '这是第二个示例视频',
url: 'https://example.com/video2.mp4',
type: 'video/mp4'
}
]
}
}
}
</script>
<style>
.video-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
}
.video-item {
border: 1px solid #ddd;
padding: 10px;
border-radius: 5px;
}
</style>
动态加载视频数据
<script>
export default {
data() {
return {
videos: [],
isLoading: false
}
},
async created() {
await this.fetchVideos();
},
methods: {
async fetchVideos() {
this.isLoading = true;
try {
const response = await fetch('https://api.example.com/videos');
this.videos = await response.json();
} catch (error) {
console.error('加载视频失败:', error);
} finally {
this.isLoading = false;
}
}
}
}
</script>
视频列表优化功能
<template>
<div>
<div v-if="isLoading">加载中...</div>
<div v-else>
<input v-model="searchQuery" placeholder="搜索视频...">
<div class="video-list">
<div
v-for="video in filteredVideos"
:key="video.id"
@click="selectVideo(video)"
:class="{ 'selected': selectedVideo === video }"
>
<video :poster="video.thumbnail" width="250">
<source :src="video.url">
</video>
<div class="video-info">
<h3>{{ video.title }}</h3>
<p>{{ video.views }}次观看</p>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
computed: {
filteredVideos() {
return this.videos.filter(video =>
video.title.toLowerCase().includes(this.searchQuery.toLowerCase())
);
}
},
methods: {
selectVideo(video) {
this.selectedVideo = video;
this.$emit('video-selected', video);
}
}
}
</script>
视频播放器组件集成
<template>
<div class="video-container">
<div class="video-player" v-if="currentVideo">
<video controls autoplay>
<source :src="currentVideo.url" :type="currentVideo.type">
</video>
<h2>{{ currentVideo.title }}</h2>
<p>{{ currentVideo.description }}</p>
</div>
<VideoList
:videos="videos"
@video-selected="setCurrentVideo"
/>
</div>
</template>
<script>
import VideoList from './VideoList.vue';
export default {
components: { VideoList },
data() {
return {
currentVideo: null,
videos: [] // 填充视频数据
}
},
methods: {
setCurrentVideo(video) {
this.currentVideo = video;
}
}
}
</script>
视频懒加载优化
// 在main.js或单独文件中
import VueLazyload from 'vue-lazyload';
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'error.png',
loading: 'loading.gif',
attempt: 1
});
// 组件中使用
<template>
<div v-for="video in videos" :key="video.id">
<img v-lazy="video.thumbnail" alt="视频缩略图">
</div>
</template>
以上代码示例展示了Vue中实现视频列表的核心功能,包括基础列表展示、数据加载、搜索过滤、视频选择和性能优化等常见需求。实际应用中可根据项目需求进行调整和扩展。







