vue使用swiper插件实现轮播图的示例

2022-04-15 0 530
目录
  • vue – 使用swiper插件实现轮播图
  • 使用watch与$nextTick解决轮播的Bug

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
    }
})

以上就是vue使用swiper插件实现轮播图的示例的详细内容,更多关于vue使用swiper插件实现轮播图的资料请关注NICE源码其它相关文章!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript vue使用swiper插件实现轮播图的示例 https://www.niceym.com/34273.html