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>
    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM