<style> img{ display:block; margin:0 auto; width:500px; height:500px; } #app li{ list-style: none; } </style> <body> <div id="app"> <img :src="img" @click="autoCg()"> <!--顯示一張圖片,並給圖片添加點擊事件--> <ul> <li v-for="(item,index) in json"></li> </ul> <button @click="prev">上一張</button> <button @click="next">下一張</button> </div> </body> <script> new Vue({ el:'#app', data:{ img:'./images/cao.jpg', json:[ "./images/cao.jpg", "./images/hua.jpg", "./images/ning.jpg", "./images/shu.jpg", ], index:0 }, methods:{ next(){ this.img = this.json[this.index++]; if(this.index > 3){ this.index = 0; //當超過圖片數量,返回第一張圖片 } }, prev(){ this.img = this.json[this.index--]; if(this.index < 0){ this.index = 3; } //當index值<0時,返回最后一張圖片 }, //點擊首張圖片觸發函數功能 autoCg(){ let self = this; //定時器,每2秒換一張圖片 setInterval(function(){ self.img = self.json [self.index++]; if(self.index > 3){ self.index = 0; } },2000); } }, }) </script>