vue 项目中使用Swiper

如何在vue项目中使用Swiper

首先安装Swiper插件
 yarn add swiper@5.2.0
 cnpm install swiper@5.2.0 -save
然后在src下面的main.js中引入
import 'swiper/css/swiper.min.css'
新建vue组件 SwiperCom.vue 写入一下代码
<template>
  <div class="swiper-container" :class="name">
    <div class="swiper-wrapper">
      <slot></slot>
    </div>
   // 分页按钮
   // <div class="swiper-pagination"></div>
  </div>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      default: ''
    }
  }
}
</script>

<style>

</style>
在需要使用轮播图的组件内引入swiper和组件SwiperCom并注册
import Swiper from 'swiper'
import SwiperCom from '../components/SwiperCom'
<script>
export default {
  components: { SwiperCom }
}
</script>
在template需要的位置使用SwiperCom

name在swiper实例化时使用,同一个页面有多个轮播图,name不能相同

<template>
  <SwiperCom name="login-banner">
     <div v-for="banner in imgList" :key="banner.id" class="swiper-slide">
       <img :src="banner.imgUrl" alt="">
     </div>
  </SwiperCom>
</template>
如果是静态的图片数据 在data中写imgList
<script>
export default {
  components: { SwiperCom }
  data() {
  	return {
	  imgList: [
        { id: 0, imgUrl: require('@/assets/login/bg1.jpg') },
        { id: 1, imgUrl: require('@/assets/login/bg2.jpg') },
        { id: 2, imgUrl: require('@/assets/login/bg3.jpg') }
      ]
	}
  }
}
</script>
Swiper实例化 实例化时添加相关的属性配置
<script>
export default {
  created() {
    this.$nextTick(() => {
      new Swiper('.login-banner', {
        loop: true, // 循环轮播
        effect: 'fade', // 淡入淡出效果 默认左右轮播
        autoplay: true // 自动轮播
        pagination: { // 分页按钮
          el: '.swiper-pagination'
        }
      })
    })
  }
}
</script>
如果时动态获取的图片 我们只需要在获取打图片后将imgList赋值,在拿到数据后实例化即可
instance.request({...... }).then(res => {
   if (res.data.data) { this.imgList= [...res.data.data] }
   /* eslint-disable no-new */
   this.$nextTick(() => {
     new Swiper(".films-banner", {
       loop: true,
       autoplay: true,
       pagination: {
         el: '.swiper-pagination'
       }
     })
   })
 })
如果需要其他样式的轮播图 访问下面的网址

https://3.swiper.com.cn/demo/index.html
挑选 >> 在新窗口打开 >> 右键查看源代码 >> 查看script标签属性即可

如果需要更多Swiper的API 访问下面的网址

https://www.swiper.com.cn/api/pagination/280.html

大哥 搞定
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值