vue实现视频列表数据
Vue实现视频列表数据
在Vue中实现视频列表数据通常涉及数据绑定、组件化以及API调用。以下是一个完整的实现方案:
数据准备与绑定
-
定义视频列表数据
在Vue组件的data中初始化视频列表数据:data() { return { videos: [ { id: 1, title: '视频1', url: 'video1.mp4', cover: 'cover1.jpg' }, { id: 2, title: '视频2', url: 'video2.mp4', cover: 'cover2.jpg' } ] } } -
动态加载数据
通过异步请求(如axios)从后端API获取数据:methods: { async fetchVideos() { try { const response = await axios.get('/api/videos'); this.videos = response.data; } catch (error) { console.error('加载视频列表失败:', error); } } }, mounted() { this.fetchVideos(); }
列表渲染与组件化
-
使用
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 :src="video.url"></video> </div> </div> -
封装视频组件
将单个视频项抽离为子组件(如VideoCard.vue):<!-- VideoCard.vue --> <template> <div class="video-card"> <img :src="cover" :alt="title"> <h3>{{ title }}</h3> <video controls :src="url"></video> </div> </template> <script> export default { props: ['id', 'title', 'url', 'cover'] } </script>
功能扩展
-
分页加载
添加分页逻辑,结合v-infinite-scroll等插件实现懒加载:
data() { return { page: 1, pageSize: 10, isLoading: false } }, methods: { async loadMore() { if (this.isLoading) return; this.isLoading = true; const response = await axios.get('/api/videos', { params: { page: this.page++, size: this.pageSize } }); this.videos.push(...response.data); this.isLoading = false; } } -
搜索过滤
通过计算属性实现客户端搜索:computed: { filteredVideos() { return this.videos.filter(video => video.title.toLowerCase().includes(this.searchQuery.toLowerCase()) ); } }
样式优化
-
响应式布局
使用CSS Grid或Flexbox实现自适应布局:.video-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; } -
视频封面占位
为未加载的视频添加占位图:<img :src="video.cover || 'placeholder.jpg'" @error="video.cover = 'fallback.jpg'" >
完整示例代码
<template>
<div>
<input v-model="searchQuery" placeholder="搜索视频">
<div class="video-list">
<VideoCard
v-for="video in filteredVideos"
:key="video.id"
v-bind="video"
/>
</div>
<button @click="loadMore" :disabled="isLoading">
{{ isLoading ? '加载中...' : '加载更多' }}
</button>
</div>
</template>
<script>
import VideoCard from './VideoCard.vue';
import axios from 'axios';
export default {
components: { VideoCard },
data() {
return {
videos: [],
searchQuery: '',
page: 1,
isLoading: false
}
},
computed: {
filteredVideos() {
return this.videos.filter(video =>
video.title.toLowerCase().includes(this.searchQuery.toLowerCase())
);
}
},
methods: {
async fetchVideos() {
const res = await axios.get('/api/videos');
this.videos = res.data;
},
async loadMore() {
this.isLoading = true;
const res = await axios.get('/api/videos', {
params: { page: this.page++ }
});
this.videos.push(...res.data);
this.isLoading = false;
}
},
mounted() {
this.fetchVideos();
}
}
</script>






