vue使用swiper外掛實現輪播圖的示例
阿新 • • 發佈:2021-05-06
hello大家好,最近我在做一個仿餓了麼的專案,我會將我的專案經驗同步到這裡,與大家分享!
vue - 使用swiper外掛實現輪播圖
下載安裝: npm install swiper --save
Msite.vue的HTML部分:
<!--在頁面msite_nav導航部分使用swiper--> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide">1</div> <div class="swiper-slide">2</div> <div class="swiper-slide">3</div> </div> <!-- swiper輪播圖圓點 --> <div class="swiper-pagination"></div> </div>
script部分引入並初始化:
<script> import Swiper from 'swiper' //同時引入swiper的 css檔案 import 'swiper/dist/css/swiper.min.css' export default { //注意要在頁http://www.cppcns.com面載入完成之後(mounted)再進行swiper的初始化 mounted () { //建立一個swiper例項來實現輪播 new Swiper('.swiper-container',{ autoplay: true,// 如果需要分頁器 pagination: { el: '.swiper-pagination',clickable: true } }) } } </script>
需要注意的是:在引入css檔案的時候,因為版本不同,引入的方式也不同,否則會因找不到相對應的css檔案而報錯,比如最新的版本
import 'swiper/swiper-bundle.min.css'
具體用法參考[Swiper官方文件]
有一個需要特別注意的是,需要在請求資料之後建立swiper例項
使用watch與$nextTick程式設計客棧解決輪播的Bug
分頁器Swiper其實應該是在輪播列表顯示(即categorys陣列有了資料)以後才初始化程式設計客棧。
最開始categorys為空陣列,有了資料才會顯示輪播列表,而要監視categorys的資料變化,就要用到watch。
// 新建watch 監聽categorys watch: { categorys (value) { // categorys陣列中有資料了 // 但介面還沒有非同步更新 } } // 刪除mounted中的new Swiper...程式碼
但其實state裡的狀態資料改變(categorys接收資料)與非同步更新介面(顯示輪播列表)是兩個步驟。所以需要等一等,介面完成非同步更新後才可以進行Swiper的初始化。
// 使用setTimeout可以實現效果,但是時機不準確 setTimeout(() => { // 建立一個Swiper例項物件,來實現輪播 new Swiper('.swiper-container',{ autoplay: true,// 如果需要分頁器 pagination: { el: '.swiper-pagination',clickable: true } }) },100)
利用vm.$nextTick( [callback] 程式設計客棧)來實現等待介面完成非同步更新就立即建立Swiper物件
// 在修改資料之後立即使用它,然後等待 DOM 更新。 this.$nextTick(() => { // 一旦完成介面更新,立即執行回撥 new Swiper('.swiper-container',{ autoplay: true,pagination: { el: '.swiper-pagination',clhttp://www.cppcns.comickable: true } })
以上就是vue使用swiper外掛實現輪播圖的示例的詳細內容,更多關於vue使用swiper外掛實現輪播圖的資料請關注我們其它相關文章!