音乐播放器

<style>
        * {
            padding: 0;
            margin: 0;
        }
        ul {list-style: none;}
        li {
            border-bottom: 1px solid yellow;
            
        }
    </style>
</head>
<body>
    <!-- 把一首歌作为一个对象(万事万物皆对象),他就应有自己的一些属性,如:歌名,作者,链接的地址等 -->
    <div id="music">
  <!-- audio类似img标签,有自己的属性,如有src属性,同时有自己的方法.  @ended(结束,audio在最后会自动调用这个事件),结束就会有下一首歌, 
autoplay:自动播放;autoloop:自动循环 --> <!--如何操作让刷新后默认播放第一首歌,但是点击不同数字,播放相对应歌曲: 1.src不能固定,因此一定要!!绑定data(数据属性)中,并先默认为第一首歌(未使用v-bind时,aodios标签中src="currenSong",
使用后src='./audios/1.mp3')--> <audio :src="currenSong" autoplay controls autoloop @ended='nextSong()'></audio> <ul> <!-- v-for对数组遍历 一个DOM(标签)元素可以加多个指令系统--> <li v-for='(item,index) in songs' @click='currentHandler(item,index)'> <h3>作者:{{item.author}}</h3> <p>{{item.name}}</p> </li> </ul> <button>上一首</button> <button @click='nextSong()'>下一首</button> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> var songs = [ /*数组 方便遍历*/ // k值为index;item是value,item为每一个{},调取可直接item.name; {id:1,src:'./audios/1.mp3',name:'la la land',author:'Ryan'}, {id:2,src:'./audios/2.mp3',name:'The Best of',author:'Skillof'}, {id:3,src:'./audios/3.mp3',name:'It My Life',author:'Bon'}, {id:4,src:'./audios/4.mp3',name:'Tender',author:'Blur'}, ] var music = new Vue ({ /*不用于id music*/ el:'#music', data:{ // 数据属性,即music对象拥有的属性 songs:songs, currenSong:'./audios/1.mp3', // 在播放当前这首歌时点击下一首;此处index需要在data中声明,默认为第1首; index:0 }, methods: { //等同于 带参数的函数item: li标签中@click='currentHandler(item) currentHandler(item){this.currenSong=item.src;}//
currentHandler(item,index){
// 为第0首时,用户先点击下一首还是直接点击列表是随机的, // 1.如果用户点击列表,需要将列表歌曲index传给data中的index,如点击第二首,则列表歌曲index为1,赋值给左侧data index为1;
若此时再点击下一首,则调用nextSong函数,this.index++变为2,即当前需要播放index为2的歌曲,即调用this.currenSong=this.songs[index].src;,
this.index=index; this.currenSong=this.songs[index].src; }, nextSong(){ // b=a++ b=1 a=2//因为等于的运算符优先级大于a++这种形式的运算符,所以先运算= 所以先b先等于a 故b的值为1,a再++ 所以为2; this.index++;/*所以输出this.index比原来大1*/ // ???[this.index]不是this.index++? this.currenSong=this.songs[this.index].src; } } }) </script>
原文地址:https://www.cnblogs.com/hudaxian/p/14310063.html