vue-实现轮播功能

html

    <!-- 轮播 -->
    <div class="s-round">
      <i class="el-icon-caret-left icon-btn icon-left" @click="preBtn"></i>
      <i class="el-icon-caret-right icon-btn icon-right" @click="nextBtn"></i>
      <!-- 家装分类 -->
      <div class="s-move">
        <div class="item-box" v-for="nl in navList" :style="scaleFun">
       轮播的区域
      </div>
    </div>

css

.s-round {
  overflow: hidden;
  position: relative;
  display: flex;
  justify-content: space-around;
}
.icon-left {
  color: #ec6e77;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}
.icon-right {
  color: #75aae0;
  position: absolute;
  right: 0px;
  top: 50%;
  transform: translateY(-50%);
}
.s-move {
  width: 1100px;
  overflow: hidden;
  display: flex;
  padding: 10px 0;
}
.item-box {
  width: 207px;
  height: 115px;
  margin-right: 8px;
  flex-shrink: 0;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 3px solid #ccc;
  transition: transform 1s;
}

JavaScript

<script>
//定义定时器
var sortInterval
export default {
  data() {
    return {
      // 移动的距离-根据子元素的长度个边距决定
      scale: -220,
      // 当前轮播元素
      arrentIndex: 0
    }
  },
  methods: {
    // 上一个
    preBtn() {
      clearInterval(sortInterval)
      if (this.arrentIndex > 0) {
        this.arrentIndex--
      }
    },
    // 下一个
    nextBtn() {
      clearInterval(sortInterval)
      if (this.arrentIndex <= this.navList.length - 6) {
        this.arrentIndex++
      } else {
      }
    }
  },
  // 定时器 实现轮播功能
    mounted() {
    var _this = this
    sortInterval = setInterval(() => {
      _this.arrentIndex++
      if (_this.arrentIndex === _this.navList.length - 4) {
        _this.arrentIndex = 0
      }
    }, 5000)
  },
  // 计算属性 动态绑定子元素的transform
    computed: {
    scaleFun() {
      var scale = this.scale
      var arrentIndex = this.arrentIndex
      return `transform:translateX(${scale * arrentIndex + 'px'})`
    }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/big_small_big/article/details/107436751