Mint UI官方文档比较简陋,没有提供Swipe组件切换到指定轮播的方法,查看其源码后,发现可以用其内部方法实现

Mint UI官方文档Swipe组件API:

参数 说明 类型 可选值 默认值
speed 动画持时(毫秒) Number 300
auto 自动播放的时间间隔(毫秒) Number 3000
defaultIndex 初始显示的轮播图的索引 Number 0
continuous 是否可以循环播放 Boolean true
showIndicators 是否显示 indicators Boolean true
prevent 是否在 touchstart 事件触发时阻止事件的默认行为。设为 true 可提高运行在低版本安卓浏览器时的性能 Boolean false
stopPropagation 是否在 touchstart 事件触发时阻止冒泡。 Boolean false

可以看到,defaultIndex参数是可以设置轮播初始化时的索引的(既显示第几个轮播块),但是当轮播组件渲染完成后,修改此参数并不会使组件切换轮播,因为此参数只在组件渲染时生效。可以让组件重新渲染来实现切换到指定轮播,代码示例如下:

<template>
  <div class="wrapper">
    <mt-swipe class="swipe" ref="swipe" :auto="0" :defaultIndex="defaultIndex">
      <mt-swipe-item>1</mt-swipe-item>
      <mt-swipe-item>2</mt-swipe-item>
      <mt-swipe-item>3</mt-swipe-item>
      <mt-swipe-item>4</mt-swipe-item>
      <mt-swipe-item>5</mt-swipe-item>
    </mt-swipe>
  </div>
</template>

<script>
import Vue from "vue";
import { Swipe, SwipeItem } from "mint-ui";
Vue.component(Swipe.name, Swipe);
Vue.component(SwipeItem.name, SwipeItem);
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      defaultIndex: 0
    };
  },
  watch: {},
  computed: {},
  methods: {
    changeSwipe(index) {
      this.defaultIndex = index; //defaultIndex是组件初始显示的轮播图的索引
      this.$refs.swipe.swipeItemCreated(); //swipeItemCreated方法是swipe组件内部的方法,可以使组件重渲染
    }
  },
  created() {},
  mounted() {}
};
</script>
<style lang="less" scoped>
.wrapper {
  .swipe {
    height: 200px;
  }
}
</style>

虽然功能实现了,不过这种思路每次都会使Swipe组件重渲染,可能会略微影响性能,如果官方能直接提供切换当前轮播的方法就好了,或者有大佬可以修改其源码自己加方法实现。还有一种切换的思路是使用组件内部的next()prev()方法,依次切换轮播直到切换到指定轮播为止,大概思路如下:

changeSwipe(index) {
    let swipeIndex = this.$refs.swipe.index; //轮播当前索引
    if (swipeIndex < index) {
	    while (this.$refs.swipe.index < index) {
	        this.$refs.swipe.next(); // 转到下一张轮播图
	    }
    } else if (swipeIndex > index) {
	    while (this.$refs.swipe.index > index) {
	        this.$refs.swipe.prev(); // 转到前一张轮播图
	    }
    }
}

这种思路没实际试验过,不知是否好用,大家可以自行拓展


版权声明:本文为u012235103原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u012235103/article/details/102502737