vue实现轮播图组件

轮播图基本上在各大网站都能看见,页面比较美观,性能交互好,接下来我们来看代码。

效果图。

一,原理

在轮播图数组imagesUrl中,通过定义一个变量索引展示对应的图片,通过点击上一张,下一张改变索引进行图片展示切换。

二,首先来看页面布局

 <div id="app">
        <div class="view">
            <div :class="{banner:true,trans:flag}"  @mouseenter="enter" @mouseleave="leave">
                <img  :src="imagesUrl[imgindex]" alt="" class="img">
            </div>
            <ul >  
                <li v-for='(item,index) in 5' @click='select(index)' :class='{con:index==sl}'></li>
             <!-- 点击小圆点切换对应图片展示 -->
            </ul>
            <button @click="prev" class="prev">上一张</button>
            <button @click="next" class="next">下一张</button>
        </div>
    </div>

三,定义变量

        imgindex:'0',//控制变量,默认显示第一张
        imagesUrl:["images/1.png","images/2.png","images/3.png","images/4.png","images/5.png"],
        flag:true,
        timer:null,//定时器

四, 点击上一张下一张切换

methods:{
       //下一张
      next:function(){
          if(this.imgindex==this.imagesUrl.length-1){
              this.imgindex=0;
          }else{
              this.imgindex++;
          }
      },
      //上一张
      prev:function(){
          if(this.imgindex<0){
              this.imgindex=this.imagesUrl.length-1
          }else{
              this.imgindex--
          }
      }
  
  }

五,点击小圆点切换

methods:{
        select(index){
            this.imgindex=index;
      //通过点击小圆点获取对应的索引,进行赋值;
        },
    }

六,加定时器自动切换

  //
 created() {
        this.timer=setInterval(this.next.bind(this),2000)
      //还可以使用箭头函数就不用bind
        this.timer=serInterval(()=>{
        this.next()
        },2000)
    },

7,鼠标经过图片清除定时器,

   methods:{
           // 鼠标移入view
           enter:function(){
            clearInterval(this.timer);
        },
            leave:function(){
            this.timer=setInterval(this.next.bind(this),3000)
        }
    }

8,样式

   <style>
        /* .banner img{
            float:left
        } */
        .img{
            float:left  
        }
        .banner{
            overflow: hidden;
        }
        .trans{
            transition:all .5s
        }
        .view{
            width: 480px;
            height: 302px;
            border:8px solid orangered;
            overflow: hidden;
            position: relative;
        }
        ul{
            width: 300px;
            height: 50px;
            position: absolute;
            bottom: 0;
            left: 90px;
        }
        ul li{
            width: 30px;
            height: 30px;
            list-style: none;
            border-radius: 50%;
            float: left;
            background: #ffffff;
        }
        .con{
            background: red;
        }
        .prev{
         position: absolute;
         top: 50%;
         left: 0;   
        }
        .next{
         position: absolute;
         top: 50%;
         right: 0;   
        }
    </style>

这样我们就完成了一个全面的轮播图!!!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。