解决swiper轮播不正常问题

783 阅读1分钟

方式A.watch + nextTick()

 watch: {//方式A.watch:1.更新数据;2.立即同步调用监听回调函数;3.异步更新界面
      newCategorys() {
        //$nextTick():将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新
        this.$nextTick(()=>{
          //创建swiper实例,swiper对象必须要在列表数据显示之后创建
          var mySwiper = new Swiper('.swiper-container', {
            autoplay: true,//可选选项,自动轮播
            pagination: { //分页器
              el: '.swiper-pagination',
            },
            loop:true
          })
        })
      }
    }

方式B.回调函数 + nextTick()

//方式B.回调函数 + nextTick(),,,获取数据的同时将回调函数传到action中被调用
this.$store.dispatch('getCategorysAction',()=>{
    this.$nextTick(()=>{
      //创建swiper实例,swiper对象必须要在列表数据显示之后创建
      var mySwiper = new Swiper('.swiper-container', {
        autoplay: true,//可选选项,自动轮播
        pagination: { //分页器
          el: '.swiper-pagination',
        },
        loop:true
      })
    })
})

方式C.利用dipatch()返回的promise ---最简洁

//方式C.await this.$store.dispatch('getCategorysAction') 
//dispatch返回的promise在数据更新且界面更新之后才成功
//创建swiper实例,swiper对象必须要在列表数据显示之后创建
var mySwiper = new Swiper('.swiper-container', {
    autoplay: true,//可选选项,自动轮播
    pagination: { //分页器
      el: '.swiper-pagination',
    },
    loop:true
})