vue項目引入swiper
swiper插件,版本不同,可能會引起引入方式以及參數設定有很大差别,很多坑都是因為版本不同造成的,
下面說下引入的問題
引入問題
網上搜到很多文章,都是直接如下圖引入,看着非常簡單,但是實際項目中,引入後項目啟動就報錯,

報類似如下錯誤
找了很久才找的一個能正确引入的文章,親測有效
以使用版本
“swiper”: “^6.3.5”,
“vue-awesome-swiper”: "^3.1.3"為例
安裝
cnpm install swiper vue-awesome-swiper --save
// 如果還報錯,可以安裝指定版本,如下
npm install vue-awesome-[email protected]6.3.5 --save
main.js引入
import VueAwesomeSwiper from 'vue-awesome-swiper'
// import style (>= Swiper 6.x)
import 'swiper/swiper-bundle.css'
Vue.use(VueAwesomeSwiper, /* { default options with global component } */)
使用
<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>
swiperOptions: {
slidesPerView: 4,//顯示個數
direction: 'vertical',
pagination: {
el: '.swiper-pagination'
},
}
computed: {
swiper() {
return this.$refs.mySwiper.swiper
}
},
mounted() {
this.swiper.slideTo(3, 1000, false)
}
以上代碼中,mounted中‘this.swiper.slideTo(3, 1000, false)’這段代碼也會報錯,報swiper找不到,具體原因未知,該代碼可以直接删掉
<style>
.swiper-container {
width: 1000px;
height: 400px;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
height: 400px;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
</style>
本文章參考
原文位址