vue3 循环播放照片功能
时间: 2023-11-01 19:07:07 浏览: 42
在 Vue 3 中,你可以使用 `v-for` 指令来循环播放照片。这里有一个简单的例子:
首先,你需要在 Vue 组件中定义一个数组,用于存储照片的 URL:
```javascript
<template>
<div>
<img :src="currentPhotoUrl" alt="Current Photo">
</div>
</template>
<script>
export default {
data() {
return {
photos: [
"https://example.com/photo1.jpg",
"https://example.com/photo2.jpg",
"https://example.com/photo3.jpg"
],
currentPhotoIndex: 0
}
},
computed: {
currentPhotoUrl() {
return this.photos[this.currentPhotoIndex];
}
},
mounted() {
setInterval(() => {
this.currentPhotoIndex = (this.currentPhotoIndex + 1) % this.photos.length;
}, 3000);
}
}
</script>
```
在上面的代码中,我们定义了一个名为 `photos` 的数组,其中包含了我们需要循环播放的照片的 URL。我们还定义了一个名为 `currentPhotoIndex` 的变量,用于跟踪当前正在显示的照片的索引。
在 `computed` 对象中,我们定义了一个名为 `currentPhotoUrl` 的计算属性,用于根据 `currentPhotoIndex` 返回当前正在显示的照片的 URL。
在 `mounted` 钩子中,我们使用 `setInterval` 函数来每隔 3 秒更新 `currentPhotoIndex`,以便循环播放照片。在更新索引时,我们使用模运算符来确保索引始终在 `0` 到 `photos.length - 1` 的范围内。
最后,在模板中,我们使用 `:src` 绑定 `currentPhotoUrl`,以便在页面中显示当前正在显示的照片。
希望这可以帮助你实现循环播放照片的功能。