Swiper 作為一款強大的前端框架,功能全面,比如實現輪播、分頁等十分好用,不過新手上來很容易踩 '坑' ,主要原因是采用的 Swiper 版本的原因,一旦解決了這個問題,那么就可以參考官方 API 文檔,實現任何自己想要的功能了。
Vue 使用 Swiper 需要安裝 Swiper 和 vue-awesome-swiper 兩個插件。
安裝的時候一定要注意版本號 ! 再次強調,一定要注意版本號 !
其中 Swiper 不要安裝 6.0 以上的版本,最好安裝版本 5 ,因為其官方 API 文檔,是 4 和 5 版本的,6.0 版本的文檔還沒有出來。
npm install Swiper@5
vue-awesome-swiper 一定要安裝 4.1.1 版本,不要安裝 3.1.3 版本。
npm install vue-awesome-swiper
如果安裝 3.1.3 版本,則配置的輪播等效果完全出不來。
這里列出一個效果圖,設置了 autoplay 的效果:
把這個組件的源碼分享給大家:
<template> <div id="swiper-wrapper"> <p class="title">商品推薦</p> <swiper ref="mySwiper" :options="swiperOption"> <swiper-slide class="recommend-item" v-for="item of recommends" :key="item.goodsId"> <img v-lazy="item.image" class="recommend-img" /> <div class="name">{{item.goodsName}}</div> <div class="price"> <span class="code">¥</span> <span class="mall-price">{{item.mallPrice}}</span> <span class="min-price">¥{{item.price}}</span> </div> <div class="bottom-btn"> <section class="left" > <van-icon name="shopping-cart" /> </section> <section class="right">查看詳情</section> </div> </swiper-slide> </swiper> </div> </template>
其中 recommends 為父組件傳遞過來的推薦商品的數據,包括商品名稱、圖片、價格等。
<script>...</script> 中最重要的就是 swiper 的配置參數: swiperOption, 所有的配置參數請參考官方 API 文檔。
<script> import { Icon } from 'vant'; import { Swiper, SwiperSlide } from 'vue-awesome-swiper' import 'swiper/css/swiper.css'; export default { components: { [Icon.name]: Icon, Swiper, SwiperSlide, }, props: { recommends: { type: Array, default: () => [] } }, data() { return { swiperOption: { slidesPerView: 3, autoplay: { delay: 1000, stopOnLastSlide: false, disableOnInteraction: false } }, } }, } </script>
SCSS規定樣式:
<style lang="scss" scoped> #swiper-wrapper { width: 100%; .title { height: 20px; line-height: 10px; padding-left: 15px; font-size: 15px; color: #FF7F50; border-bottom: 1px #eee solid; margin-bottom: 0px; } & .recommend-item { width: calc((1 / 3) * 100%) !important; overflow: hidden; border-right: 1px #eee solid; text-align: center; padding-bottom: 5px; &:last-child { border: none } img { width: 80%; } .name { padding: 5px 0 0 7.5px; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 13px; } .price { padding: 5px 0 0 7.5px; .code { font-size: 14px; } .mall-price { font-size: 15px; } .min-price { padding-left: 6px; font-size: 12px; display: inline-block; text-decoration: line-through; color: #999; } } .bottom-btn { margin-top: 4px; padding: 0 7.5px 0 7.5px; display: flex; .left { width: 30%; padding: 7.5px 2px; background-color: #FECA3A; color: #fff; padding: 2px; border-radius: 5px 0 0 4px; } .right { font-size: 12px; padding: 3px; flex: 1; text-align: center; box-sizing: border-box; background-color: #6A5ACD; color: #fff; border-radius: 0 5px 5px 0; } } } } </style>
如有任何疑問問題,歡迎留言哦。