请问,我想把audio做成一个组件,ulli做成一个组件,button做成一个组件,其中musicData由ulli组件的created()钩子函数生成并挂载到vm实例data上,button组件为具名组件,该怎么写?最好有完整的代码,谢谢
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./js/v2.6.10/vue.js"></script>
<style>
*{
padding: 0;
margin: 0;
}
ul{
list-style: none;
}
ul li{
margin: 20px;
padding: 10px 5px;
border-radius: 3px;
}
ul li.active{
background-color: #d2e2f3;
}
</style>
</head>
<body>
<div id="app">
<audio :src="currentMusicSrc" ref="audio" @pause="" @play="" @ended="handleNext(currentIndex)" autoplay controls ></audio>
<div>
<ul >
<li :class="{active: index === currentIndex}" v-for="(item, index) in musicData" :key="item.id" @click="handleClick(item.songSrc, index)">
<h2>{{item.id}}-歌名:{{item.name}}</h2>
<p>{{item.author}}</p>
</li>
</ul>
<button @click="handleNext(currentIndex)">>>下一首</button>
<button @click="handleRandom()">随机播放</button>
<button @click="handlePlay()">{{isPlaying ? '⏸' : '▶'}} </button>
<button @click="handleLast(currentIndex)">上一首<<</button>
</div>
</div>
<script>
const musicData = [
{
id: 1,
name: "于荣光 - 少林英雄",
author: "于荣光",
songSrc: "./static/于荣光 - 少林英雄.mp3",
},
{
id: 2,
name: "Joel Adams - Please Dont Go",
author: "Joel Adams",
songSrc: "./static/Joel Adams - Please Dont Go.mp3",
},
{
id: 3,
name: "MKJ - Time",
author: "MKJ",
songSrc: "./static/MKJ - Time.mp3",
},
{
id: 4,
name: "Russ - Psycho (Pt. 2)",
author: "Russ",
songSrc: "./static/Russ - Psycho (Pt. 2).mp3",
},
];
const vm = new Vue({
el: "#app",
data() {
return {
musicData,
currentMusicSrc: musicData[0].songSrc,
currentIndex: 0,
isPlaying : true
};
},
methods: {
handleClick(src, index) {
this.currentMusicSrc = src;
this.currentIndex = index;
},
handleNext(currentIndex) {
currentIndex += 1;
if(currentIndex >= musicData.length) {
currentIndex = 0;
}
this.currentMusicSrc = musicData[currentIndex].songSrc;
this.currentIndex = currentIndex;
},
handleLast(currentIndex) {
currentIndex -= 1;
if(currentIndex < 0) {
currentIndex = musicData.length - 1;
}
this.currentMusicSrc = musicData[currentIndex].songSrc;
this.currentIndex = currentIndex;
},
selectFrom(startNumber, endNumber) {
const choice = endNumber - startNumber + 1;
return Math.floor(Math.random() * choice + startNumber)
},
handleRandom() {
const randomIndex = this.selectFrom(0, musicData.length - 1);
this.currentMusicSrc = musicData[randomIndex].songSrc;
this.currentIndex = randomIndex;
console.log(`随机index:${randomIndex}-${musicData[randomIndex].name}`);
},
paly: function() {
this.isPlaying = true;
//// 数据改变 DOM 还没有更新
this.$nextTick(() => {
//在修改数据之后立即使用这个方法,获取更新后的 DOM
this.$refs.audio.play();
})
},
pause: function() {
this.isPlaying = false;
this.$nextTick(() => {
this.$refs.audio.pause();
})
},
handlePlay() {
if(!this.isPlaying) {
this.paly();
} else {
this.pause();
}
}
}
});
</script>
</body>
</html>