1. 程式人生 > >vue中輪播圖的實現

vue中輪播圖的實現

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div id="app">
    <!--檢視-->
    <img :src="images[currentIndex].imgSrc"
alt="" @click="imgHandler"> <br> <button @click="prevHandler">上一張</button> <button @click="nextHandler">下一張</button> </div> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script src='./vue.js'></script> <
script> let vm = new Vue({ // 宣告變數 例項化一個物件vm(指的是vue的例項) el:"#app", //繫結根元素 data(){ return{ images:[ //資料 {id:1,imgSrc:"img/1.jpg"}, {id:2,imgSrc:"img/2.jpg"}, {id:3,imgSrc:"img/3.jpg"},
// {id:4,imgSrc:"img/4.jpg"}, ], currentIndex:0 //一開始設定為 0 } }, methods:{// 物件內容是js函式 nextHandler(e){ console.log(e); this.currentIndex++; //更改圖片地址 if (this.currentIndex == 3){ //js的if判斷語句 this.currentIndex = 0; } }, prevHandler(e) { console.log(e); this.currentIndex--; //更改圖片地址 if (this.currentIndex == 0) { //js的if判斷語句 this.currentIndex = 3; } }, imgHandler(e){ //每一個事件都有一個event物件, 冒泡阻止預設事件學的 console.log(e.target);//當前目標物件 <img src="img/1.jpg" alt> console.log(this); //例項化裡面的物件this 指的都是當前例項化物件 } }, //create() 元件建立完成, 元件建立完成立馬往後臺發ajax // ajax vue的鉤子函式 // created(){ // // console.log(this); //就是當前的vm // setInterval(function(){ // console.log(this);//this是window物件 但是想把this的指向改成vm 所以把匿名函式改成箭頭函式 // },1000) // } created(){ // this的指向問題 ************* 能用箭頭函式不用匿名函式 //匿名函式改成箭頭函式 this代指vue setInterval( ()=>{ console.log(this);//this是 vue 物件 },1000)//自動迴圈播放圖片 1秒播放一次 } }) </script> </body> </html>