vue做的简单轮播图

这个轮播图有两种方式循环进行图片的切换,一种是点击左箭头或右箭头来切换上一张或下一张,一种是设置定时器,每过5秒自动切换下一张图片。

先做出轮播图的基本样式,再来做切换的js代码。我使用数组来保存图片的地址,注意,数组里的图片相对地址是根据你html文件的位置来的,因为你是要使用在html代码里,我一开始根据js文件的位置来,导致出现裂图。使用v-bind指令,绑定img标签的src属性: <img :src="imgArr[index]" id="pic">来进行图片的切换,这里的index是数组索引,我们从第一张图片开始,所以我们在data里设置index:0。再使用v-on指令来设置点击左箭头和右箭头进行图片切换。当我们点击左箭头时,使用函数pre,我们先判断此时的index,假如这时index=0,我们将index设置成3(3是最后一张图片的索引),点击右箭头时同理,假如此时的index=3,则设置index=0,这样即可达到一种循环播放的效果。

设置每过5秒切换下一张图片,我使用的是setInterval方法,在mounted()函数里边使用setInterval(), setIntervar调用的方法在methods里写,在mounted里调用,注意:setInterval的第一个参数不加括号,第二个参数是时间。

效果如下:

 代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片切换</title>
    <link rel="stylesheet" href="css/index.css">
</head>
<body>
    <div id="app">
        <img :src="imgArr[index]" id="pic">
        <img src="images/zuojiantou.png" alt="" id="left" @click="pre" >
        <img src="images/youjiantou.png" alt="" id="right"@click="next">
    </div>
    <script src="../../vue/vue.js"></script>
    <script src="js/index.js"></script>
</body>
</html>
html
div{
    width: 400px;
    height: 300px;
    margin: 0 auto;
    position: relative;
}
#pic{
    width: 400px;
    height: 300px;
}
#left{
    position: absolute;
    left: 0px;
    bottom: 150px;
    width: 40px;
}
#right{
    position: absolute;
    right: 0px;
    bottom: 150px;
    width: 40px;
}
css
var app=new Vue({
    el:'#app',
    data: {
        imgArr:
        ["images/1920x1080.jpg",
        "images/1920x1080a.jpg",
        "images/1920x1080b.jpg",
        "images/1920x1080c.jpg"],
        index:0,
        
        
    },
    methods: {
        pre:function(){
            if(this.index>0){
                this.index--
                
            }
            else if(this.index==0){
                this.index=3
            }
            
        },
        next:function(){
            if(this.index<3){
                this.index++
            }
            else if(this.index==3){
                this.index=0
            }
        },
       
    }, 
    mounted() {
            this.next();//先调用一遍
            setInterval(this.next,5000);
        },
})
js
 
原文地址:https://www.cnblogs.com/spare-ribs/p/12607668.html