1.首先是安装
npm install swiper vue-awesome-swiper --save
2.引入模块
全局引入:
import Vue from 'vue'
import VueAwesomeSwiper from 'vue-awesome-swiper'
// import style
import 'swiper/css/swiper.css'
Vue.use(VueAwesomeSwiper,)
本地引入:
import { Swiper, SwiperSlide, directive } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
export default {
components: {
Swiper,
SwiperSlide
},
directives: {
swiper: directive
}
}
3.组件中使用:
简单写个小案例,注:我这是拷贝原网站的,它的格式也是有要求的,所以不能自己改哦
<template>
<swiper ref="mySwiper" :options="swiperOptions">
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide>
<swiper-slide>Slide 3</swiper-slide>
<swiper-slide>Slide 4</swiper-slide>
<swiper-slide>Slide 5</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
export default {
name: 'carrousel',
data() {
return {
swiperOptions: {
pagination: {
el: '.swiper-pagination'
},
// Some Swiper option/callback...
}
}
},
computed: {
swiper() {
return this.$refs.mySwiper.$swiper
}
},
mounted() {
console.log('Current Swiper instance object', this.swiper)
this.swiper.slideTo(3, 1000, false)
}
}
</script>
然后你就会发现你报错了哈哈哈
报错代码:
This dependency was not found:
* swiper/css/swiper.css in ./src/main.js
这个是因为你引入的css根本就找不到路径,
就是这个:
import 'swiper/css/swiper.css'
但是你删除它,引入6版本的css样式,它就是出不来小点点,只能自己手动滑动,其他的都实现不了。。。
后来的解决方案:
main.js中全局引入
import {
Swiper as SwiperClass,
Pagination,
Mousewheel,
Autoplay
} from "swiper/core";
import getAwesomeSwiper from "vue-awesome-swiper/dist/exporter";
import 'swiper/swiper-bundle.css'
SwiperClass.use([Pagination, Mousewheel, Autoplay]);
Vue.use(getAwesomeSwiper(SwiperClass));
局部引入:
import Vue from 'vue'
import {
Swiper as SwiperClass,
Pagination,
Mousewheel,
Autoplay
} from "swiper/core";
import 'swiper/swiper-bundle.css'
import getAwesomeSwiper from 'vue-awesome-swiper/dist/exporter'
SwiperClass.use([Pagination, Mousewheel, Autoplay])
const { Swiper, SwiperSlide ,directive} = getAwesomeSwiper(SwiperClass);
js代码
export default {
components: {
Swiper,
SwiperSlide
},
directives: {
swiper: directive
}, //这个如果是全局引入,就可以不用写
data() {
return {
banners: [
"https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1603365312,3218205429&fm=26&gp=0.jpg",
"https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg",
"https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3892521478,1695688217&fm=26&gp=0.jpg"
],
swiperOption: {
autoplay: true,
pagination: {
el: ".swiper-pagination"
},
mousewheel: true
// ...
}
};
},
}
页面布局也搞一下嗯:
<template>
<div v-swiper:mySwiper="swiperOption">
<div class="swiper-wrapper">
<div class="swiper-slide" :key="banner" v-for="banner in banners">
<img :src="banner" />
</div>
</div>
<div class="swiper-pagination"></div>
</div>
</template>
然后就能实现小点点的效果啦,几天的烦恼就解决了。
我觉得我最大的问题是:
想要实现小点点和自动播放功能,刚开始的时候,我就只想着如何将布局给弄出来,后来看了一篇博客,给了我灵感。最重点的点就是Swiper Vue.js使用Swiper的核心版本(没有任何其他组件)。如果要使用导航,分页和其他组件,则必须首先引入它们。
有bug的时候一定要静下心来想想解决的方案,解决那刻是真的想飞。。。