Vue 实现图片视频轮播,自定义时长切换内容
Vue 可以通过组件和计时器来实现图片视频轮播单独显示时长切换。
首先,我们需要创建一个轮播组件,包含一个图片或视频列表和一个计时器。计时器用于定时切换图片或视频。
<template>
<div class='carousel'>
<div v-for='(item, index) in items' :key='index' v-show='currentIndex === index'>
<img v-if='item.type === 'image'' :src='item.src' />
<video v-else :src='item.src' controls></video>
</div>
</div>
</template>
<script>
export default {
props: {
items: Array,
duration: Number,
},
data() {
return {
currentIndex: 0,
timerId: null,
};
},
mounted() {
this.startTimer();
},
methods: {
startTimer() {
this.timerId = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.items.length;
}, this.items[this.currentIndex].duration || this.duration);
},
stopTimer() {
clearInterval(this.timerId);
},
},
watch: {
currentIndex() {
this.stopTimer();
this.startTimer();
},
},
};
</script>
在上面的代码中,我们定义了一个 carousel 组件,它包含一个图片或视频列表和一个计时器。我们使用 v-for 指令遍历图片或视频列表,并使用 v-show 指令根据当前索引值显示当前图片或视频。我们还定义了一个 currentIndex 变量表示当前索引值,以及一个 timerId 变量表示计时器的 ID。
在组件的 mounted 生命周期钩子中,我们调用 startTimer 方法启动计时器。在该方法中,我们使用 setInterval 函数每隔一定时间切换图片或视频。切换的方式是将当前索引值加1,如果超出了列表长度,则将索引值重置为0。
我们还定义了一个 stopTimer 方法,用于停止计时器。我们在组件的 watch 钩子中监听 currentIndex 变量的变化,并在变化时停止计时器并重新启动计时器。
最后,我们在组件的 props 中定义了 items 和 duration 两个属性。items 表示图片或视频列表,每个元素包含一个 type 属性表示是图片还是视频,以及一个 src 属性表示图片或视频的 URL。duration 表示每个图片或视频显示的时间,如果某个图片或视频需要显示的时间不同于其他图片或视频,则可以为其设置 duration 属性。
使用该组件时,我们只需要传入图片或视频列表和每个图片或视频需要显示的时间即可:
<template>
<div>
<carousel :items='items' :duration='duration' />
</div>
</template>
<script>
import Carousel from './Carousel.vue';
export default {
components: {
Carousel,
},
data() {
return {
items: [
{ type: 'image', src: 'img1.jpg', duration: 3000 },
{ type: 'image', src: 'img2.jpg', duration: 5000 },
{ type: 'video', src: 'video1.mp4' },
{ type: 'image', src: 'img3.jpg', duration: 2000 },
],
duration: 4000,
};
},
};
</script>
在上面的代码中,我们创建了一个名为 Carousel 的组件,并将其引入到父组件中。我们还定义了一个 items 数组,包含了四个元素,分别是两张图片、一段视频和一张图片,其中第一张图片需要显示3秒,第二张图片需要显示5秒,第三个元素是视频,不需要显示时间限制,第四张图片需要显示2秒。我们还定义了一个 duration 变量,表示每个图片或视频默认显示的时间为4秒。最后,我们将 items 和 duration 传递给 Carousel 组件即可。
原文地址: https://www.cveoy.top/t/topic/oeLf 著作权归作者所有。请勿转载和采集!