注意: methods和computed里的东西不能重名
<div id='app'> <audio :src="currentSrc" controls autoplay @ended='handleEnded'></audio> <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'>下一首</button> </div> <script src="./vue.js"></script> <script> const musicData = [{ id: 1, name: '杨宗纬 - 空白格', author: '杨宗纬', songSrc: '杨宗纬 - 空白格 (Live).mp3' }, { id: 2, name: '杨宗纬 - 其实都没有', author: '杨宗纬', songSrc: '杨宗纬 - 其实都没有.flac' }, { id: 3, name: '杨宗纬 - 我想要', author: '杨宗纬', songSrc: '杨宗纬 - 我想要 (Live).flac' } ]; new Vue({ el: '#app', data: { musicData, currentSrc: '杨宗纬 - 空白格 (Live).mp3', currentIndex: 0 }, methods: { handleClick(src, index) { this.currentSrc = src; this.currentIndex = index; }, handleEnded() { // // 下一首的播放 // this.currentIndex++; // this.currentSrc = this.musicData[this.currentIndex].songSrc; this.handleNext(); }, handleNext() { this.currentIndex++; if (this.currentIndex === this.musicData.length) { this.currentIndex = 0; } this.currentSrc = this.musicData[this.currentIndex].songSrc } } }) </script>
使用计算机属性还是methods取决于你是否需要缓存,当遍历大数组和做大量计算时,应当使用计算机属性,除非你不希望得到缓存。