vue简单实现轮播图

一 准备数据
(1)定义一个dataList,里面存放我们的图片
dataList:['../../static/images/300.jpg','../../static/images/301.jpg']
(2)currentIndex:来表示当时当前图片的索引

currentIndex:0

二、显示一张图片

 <div class="banner">

    <div class="item">
      <img :src="dataList[currentIndex]">

    </div>
   </ul>
 </div>

这样就显示了索引为0的图片了
三、遍历dataList,通过索引来访问图片

 <div class="banner">

    <div class="item">
      <img :src="dataList[currentIndex]">

    </div>
   <ul>
     <li v-for="(data,index) in dataList" :key="index" @click="setCurrentIndex(index)" :style="{backgroundColor:currentIndex==index?'green':''}">
       第{{index+1}}张
     </li>
   </ul>
 </div>

写个setCurrentIndex方法

 setCurrentIndex (index) {
      this.currentIndex=index
    }

这样我们就可以点击图片的索引访问了
四、实现图片定时轮播
写一个计算属性nextIndex

nextIndex () {
      if (this.currentIndex==this.dataList.length-1){
        return 0
      } else {

        return this.currentIndex+1
      }
      console.log('currentIndex:' + this.currentIndex)
      return this.currentIndex
    }

在设置个定时器

 setInterval(() => {
      this.setCurrentIndex(this.nextIndex)
    },3000)

这样就可以实现图片的轮播以及点击相应的图片索引访问了
在这里插入图片描述
完整代码:

<template>
 <div class="banner">

    <div class="item">
      <img :src="dataList[currentIndex]">

    </div>
   <ul>
     <li v-for="(data,index) in dataList" :key="index" @click="setCurrentIndex(index)" :style="{backgroundColor:currentIndex==index?'green':''}">
       第{{index+1}}张
     </li>
   </ul>
 </div>

</template>

<script>
export default {
  name: "Test",
  data () {
    return {
      dataList:['../../static/images/300.jpg','../../static/images/301.jpg'],
      currentIndex:0
    }
  },
  methods: {
    setCurrentIndex (index) {
      this.currentIndex=index
    }

  },
  created() {
    console.log( this.dataList.length)
  },

  computed: {
    nextIndex () {
      if (this.currentIndex==this.dataList.length-1){
        return 0
      } else {

        return this.currentIndex+1
      }
      console.log('currentIndex:' + this.currentIndex)
      return this.currentIndex
    }
  },
  mounted() {

    setInterval(() => {
      this.setCurrentIndex(this.nextIndex)
    },3000)
  }
}
</script>

<style scoped  lang="less">
 
  ul{
    list-style-type: none;
    display: flex;

    li{
      width: 50px;
      &:hover{
        cursor: pointer;
      }
    }
  }

</style>

  • 6
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值