一、在vue项目中安装swiper
cnpm install swiper@5.4.5 -S
cnpm install vue-awesome-swiper@3.1.3 -S
二、在main.js中引入swiper.css
import 'swiper/css/swiper.css'
三、在组件中使用
1、引入必要的组件
import { swiper, swiperSlide } from "vue-awesome-swiper";
2、注册子组件
components: {
swiper,
swiperSlide
}
3、结构添加
data() { return { swiperOptions: { loop: true, speed: 2000, autoplay: { delay: 3000, stopOnLastSlide: false, disableOnInteraction: false, }, // 显示分页 pagination: { el: ".swiper-pagination", clickable: true, //允许分页点击跳转 }, // 设置点击箭头 navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, // 修改默认点击左右箭头样式 // navigation: { // nextEl: ".swiper-button-next", //prevEl: ".swiper-button-prev", //}, }, }; },
4、template 中使用
①template 箭头放到轮播图内
<template> <div class="wrapper"> <swiper ref="mySwiper" v-bind:options="swiperOptions"> <swiper-slide v-for="(item, index) in 5" v-bind:key="index"> {{item}} </swiper-slide> <div class="swiper-pagination" slot="pagination"></div> <div class="swiper-button-prev" slot="button-prev"></div> <div class="swiper-button-next" slot="button-next"></div> </swiper> </div> </template>
②template 箭头放到轮播图外
<template> <div class="wrapper"> <swiper ref="mySwiper" v-bind:options="swiperOptions"> <swiper-slide v-for="(item, index) in 5" v-bind:key="index"> {{item}} </swiper-slide> <div class="swiper-pagination" slot="pagination"></div> </swiper> <div class="swiper-button-prev swiper-button-prevsp" slot="button-prev"></div> <div class="swiper-button-next swiper-button-nextsp" slot="button-next"></div> </div> </template>
5、修改默认样式
.swiper-container { background: #f00; } .swiper-slide { height: 180px; } // 若是修改默认样式,以下内容必须填写 .wrapper{ position: relative; } .wrapper .swiper-button-nextsp, .wrapper .swiper-button-prevsp { position: absolute; width: 40px; height: 40px; display: inline-block; text-align: center; line-height: 40px; cursor: pointer; z-index: 22222; } .wrapper .swiper-button-prevsp { background: url("~@/assets/images/left.png") no-repeat center center; left: 0; top: 50%; transform: translateY(-50%); } .wrapper .swiper-button-prevsp::after,.wrapper .swiper-button-nextsp::after{ content: ''; } .wrapper .swiper-button-prevsp:hover { background: url("~@/assets/images/leftCur.png") no-repeat center center; } .wrapper .swiper-button-nextsp { background: url("~@/assets/images/right.png") no-repeat center center; right: 0; top: 50%; transform: translateY(-50%); } .wrapper .swiper-button-nextsp:hover { background: url("~@/assets/images/rightCur.png") no-repeat center center; }
大功告成!