vue - 使用swiper插件实现轮播图

4,678 阅读1分钟

hello大家好,最近我在做一个仿饿了么的项目,我会将我的项目经验同步到这里,与大家分享!

vue - 使用swiper插件实现轮播图

下载安装: npm install swiper --save

Msite.vue的HTML部分:

<!--在页面msite_nav导航部分使用swiper-->
<div class="swiper-container">
	<div class="swiper-wrapper">
        <div class="swiper-slide">1</div>
        <div class="swiper-slide">2</div>
        <div class="swiper-slide">3</div>
    </div>
    <!-- swiper轮播图圆点 -->
    <div class="swiper-pagination"></div>
</div>

script部分引入并初始化:

<script>
import Swiper from 'swiper'
//同时引入swiper的 css文件
import 'swiper/dist/css/swiper.min.css'
export default {
  //注意要在页面加载完成之后(mounted)再进行swiper的初始化
  mounted () {
    //创建一个swiper实例来实现轮播
    new Swiper('.swiper-container', {
      autoplay: true,
      // 如果需要分页器
      pagination: {
        el: '.swiper-pagination',
        clickable: true
      }
   })
  }
}
</script>

需要注意的是:在引入css文件的时候,因为版本不同,引入的方式也不同,否则会因找不到相对应的css文件而报错,比如最新的版本

import 'swiper/swiper-bundle.min.css'

具体用法参考[Swiper官方文档]

有一个需要特别注意的是,需要在请求数据之后创建swiper实例

使用watch与$nextTick解决轮播的Bug

  • 分页器Swiper其实应该是在轮播列表显示(即categorys数组有了数据)以后才初始化。

  • 最开始categorys为空数组,有了数据才会显示轮播列表,而要监视categorys的数据变化,就要用到watch

    // 新建watch 监听categorys
    watch: {
        categorys (value) { // categorys数组中有数据了
        	// 但界面还没有异步更新
        }
    }
    // 删除mounted中的new Swiper...代码
    
  • 但其实state里的状态数据改变(categorys接收数据)与异步更新界面(显示轮播列表)是两个步骤。所以需要等一等,界面完成异步更新后才可以进行Swiper的初始化。

    // 使用setTimeout可以实现效果, 但是时机不准确
    setTimeout(() => {
    	// 创建一个Swiper实例对象, 来实现轮播
    	new Swiper('.swiper-container', {
              autoplay: true,
              // 如果需要分页器
              pagination: {
                el: '.swiper-pagination',
                clickable: true
              }
    	})
    }, 100)
    
  • 利用vm.$nextTick( [callback] )来实现等待界面完成异步更新就立即创建Swiper对象

    // 在修改数据之后立即使用它,然后等待 DOM 更新。
    this.$nextTick(() => {
    	// 一旦完成界面更新, 立即执行回调
        new Swiper('.swiper-container', {
        	autoplay: true,
        	pagination: {
        	el: '.swiper-pagination',
        	clickable: true
        }
    })
    

谢谢大家!希望留下您阅读的痕迹(点赞,关注,评论) 嘿嘿!