uniapp 实现类似抖音那种 滑动播放视频 的组件,写代码
时间: 2023-12-26 21:04:01 浏览: 252
<template>
<view class="video-list" @scroll="onScroll">
<view v-for="(video, index) in videos" :key="index" class="video-item">
<video :src="video.url" :poster="video.poster" @play="onPlay(index)" @pause="onPause(index)" ref="videoRef" />
<view class="video-info">
<image :src="video.avatar" class="avatar" />
<text class="nickname">{{ video.nickname }}</text>
<text class="desc">{{ video.desc }}</text>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
videos: [
{
url: 'https://example.com/video1.mp4',
poster: 'https://example.com/poster1.png',
avatar: 'https://example.com/avatar1.png',
nickname: 'User1',
desc: 'Video 1'
},
{
url: 'https://example.com/video2.mp4',
poster: 'https://example.com/poster2.png',
avatar: 'https://example.com/avatar2.png',
nickname: 'User2',
desc: 'Video 2'
},
{
url: 'https://example.com/video3.mp4',
poster: 'https://example.com/poster3.png',
avatar: 'https://example.com/avatar3.png',
nickname: 'User3',
desc: 'Video 3'
}
],
playingIndex: -1
};
},
methods: {
onPlay(index) {
if (this.playingIndex !== -1 && this.playingIndex !== index) {
this.pauseVideo(this.playingIndex);
}
this.playingIndex = index;
},
onPause(index) {
if (this.playingIndex === index) {
this.playingIndex = -1;
}
},
pauseVideo(index) {
const video = this.$refs.videoRef[index];
if (video) {
video.pause();
}
},
onScroll(event) {
const scrollTop = event.detail.scrollTop;
const windowHeight = uni.getSystemInfoSync().windowHeight;
const videoList = this.$refs.videoList;
const videoItems = this.$refs.videoRef;
for (let i = 0; i < videoItems.length; i++) {
const item = videoItems[i];
const rect = item.$el.getBoundingClientRect();
if (rect.top < windowHeight && rect.bottom > 0) {
item.play();
} else {
item.pause();
}
}
}
}
};
</script>
<style>
.video-list {
display: flex;
flex-direction: column;
}
.video-item {
position: relative;
margin-bottom: 20px;
}
.video-info {
position: absolute;
bottom: 10px;
left: 10px;
display: flex;
align-items: center;
color: #fff;
}
.avatar {
width: 30px;
height: 30px;
border-radius: 50%;
margin-right: 10px;
}
.nickname {
font-size: 14px;
font-weight: bold;
margin-right: 10px;
}
.desc {
font-size: 12px;
}
</style>
阅读全文