吼吼吼,你来了呀,是不是又遇到问题了,又开始掉头发了,我来拯救你了我已经掉过头发了,不允许你再掉了。v-htnl
首先我们分析一下原因,为什么swiper里用图片(image)就很丝滑, 但是使用video就卡的一批,卡的怀疑人生呢,我也不知道百度说是因为video的层级要比swiper的高,所以你滑动没啥用。
解决方案:1、用nvue (百度说的,我没用因为我菜) 2、v-html (是不是豁然开朗了)
废话不多说上代码!!
<template>
<view>
<view class="index_banner">
<swiper class="swipers-box" :indicator-dots="false" :autoplay="false" interval="5000" duration="500"
:circular="true" @change="onSwiperChange" :current="current">
<swiper-item v-for="(item, index) in bannerList" :key='index'>
<view @tap="goPage(item.url)">
<div v-html="getVideoHtml(item.videoUrl, index)"></div>
</view>
</swiper-item>
</swiper>
</view>
<u-gap height="8" bgColor="#F6F6F7"></u-gap>
</view>
</template>
<script>
export default {
name: "index-video",
props: {
title: {
type: String,
default: global.name
},
bannerList: {
type: Array,
default () {
return [{
videoUrl: '/static/video/video_1.mp4'
},
{
videoUrl: '/static/video/video_2.mp4'
},
{
videoUrl: '/static/video/video_3.mp4'
},
{
videoUrl: '/static/video/video_4.mp4'
},
{
videoUrl: '/static/video/video_5.mp4'
},
];
}
}
},
data() {
return {
currentIndex: 0,
current: 3
};
},
mounted() {
this.playVideo(this.currentIndex); // 组件挂载后播放当前视频
this.checkVideoEnded(); // 开始检查视频是否结束
},
methods: {
getVideoHtml(videoUrl, index) {
return `<video id="video-${index}" class="video-class"
controlslist="nodownload"
controls="controls"
src="${videoUrl}"
style="width: 100%; height: 100%;"></video>`;
},
checkVideoEnded() {
this.videoCheckInterval = setInterval(() => {
const video = document.getElementById(`video-${this.currentIndex}`);
if (video && video.ended) {
this.videoEnded(this.currentIndex);
}
}, 1000); // 每秒检查一次
},
videoEnded(index) {
console.log("当前结束索引",index)
this.stopVideo(index);
this.currentIndex = (index + 1) % this.bannerList.length;
// this.$refs.swiper.swipeNext();
this.current = this.currentIndex; // 通过改变current,自动切换
this.playVideo(this.currentIndex);
},
stopVideo(index) {
const video = document.getElementById(`video-${index}`);
if (video) {
video.pause();
video.currentTime = 0;
}
},
playVideo(index) {
const video = document.getElementById(`video-${index}`);
if (video) {
video.play().catch((err) => {
console.error("Video play failed:", err);
});
}
},
onSwiperChange(e) {
const newIndex = e.detail.current;
if (newIndex !== this.currentIndex) {
this.stopVideo(this.currentIndex);
this.currentIndex = newIndex;
this.playVideo(this.currentIndex);
}
},
goPage(url) {
// 处理页面跳转
},
},
beforeDestroy() {
clearInterval(this.videoCheckInterval); // 清理定时器
},
};
</script>
<style lang="scss" scoped>
.index_banner {
padding: 0 10rpx;
}
.swipers-box {
width: 100%;
height: 380rpx;
border-radius: 10rpx;
}
</style>
视频资源自己替换哈,,可以拉进度条, 暂停 放大播放 , 自动播放下一个