Vue 代码循环播放按钮无法循环播放问题的解决方法
<template>
<div class="body">
<video src="@/assets/videos/金木1.mp4" muted loop autoplay style="position: absolute; top: 0px; left: 0px;height:170%;width:120%;"></video>
<div class="shell">
<div class="cover">
<img src="@/assets/金木3.jpg" alt="">
</div>
<div class="info">
<div class="title">KANEKI</div>
<div class="singer">金木</div>
</div>
<div class="volume-box" :class="{ active: showVolumeBox }">
<span class="volume-down" @click="handleVolumeDown"><i class="material-icons">remove</i></span>
<input type="range" class="volume-range" step="1" v-model="volume" min="0" max="100">
<span class="volume-up" @click="handleVolumeUp"><i class="material-icons">add</i></span>
</div>
<div class="btn-box">
<i class="material-icons repeat" :class="{ active: loop }" @click="handleRepeat">repeat</i>
<i class="material-icons favorite" :class="{ active: favorite }" @click="handleFavorite">favorite</i>
<i class="material-icons volume" @click="toggleVolumeBox">volume_up</i>
</div>
<div class="music-box">
<input type="range" class="seekbar" step="1" v-model="currentTime" min="0" :max="duration" @input="handleSeekBar">
<audio class="music-element" ref="music" :volume="volume">
<source src="@/assets/videos/南辰Music - 病变(纯音乐).mp3">
</audio>
<span class="current-time">{{ formatTime(currentTime) }}</span>
<span class="duration">{{ formatTime(duration) }}</span>
<span class="play" @click="handlePlay">
<i class="material-icons" v-if="!playing">play_arrow</i>
<i class="material-icons" v-else>pause</i>
</span>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
playing: false,
loop: false,
favorite: false,
volume: 80,
showVolumeBox: false,
currentTime: 0,
duration: 0,
isLooping: false // 新增属性
};
},
methods: {
handlePlay() {
this.playing = !this.playing;
const music = this.$refs.music;
if (this.playing) {
music.play();
} else {
music.pause();
}
music.addEventListener('ended', () => {
this.playing = false;
if (this.isLooping) { // 判断是否循环
music.currentTime = 0;
music.play();
}
});
},
handleRepeat() {
this.loop = !this.loop;
this.isLooping = this.loop; // 更新 isLooping
},
handleFavorite() {
this.favorite = !this.favorite;
},
handleSeekBar() {
const music = this.$refs.music;
music.currentTime = this.currentTime;
},
handleVolumeDown() {
this.volume = Math.max(this.volume - 20, 0);
this.$refs.music.volume = this.volume / 100;
},
handleVolumeUp() {
this.volume = Math.min(this.volume + 20, 100);
this.$refs.music.volume = this.volume / 100;
},
toggleVolumeBox() {
this.showVolumeBox = !this.showVolumeBox;
},
formatTime(time) {
const minutes = Math.floor(time / 60);
const seconds = Math.floor(time % 60);
return `${minutes}:${seconds}`;
}
},
mounted() {
const music = this.$refs.music;
music.addEventListener('loadeddata', () => {
this.duration = music.duration;
});
music.addEventListener('timeupdate', () => {
this.currentTime = music.currentTime;
});
}
};
</script>
原文地址: https://www.cveoy.top/t/topic/qEZL 著作权归作者所有。请勿转载和采集!