vue引入swiper的報錯以及swiper在vue中的交互事件處理


安裝遇到找不到 css的問題,百度查了一些帖子也不行,可能是swiper 升級6.0后的一些變化導致

安裝成功的帖子:轉載於:https://www.jianshu.com/p/0150d2ee109f

以防丟失,再記錄一下:

坑1

以前只需要安裝vue-awesome-swiper就夠了
現在需要weiper一起安裝才行

坑2

按官網教程操作后vue會報錯 找不到swiper.css
因為版本不同 項目目錄變了 點開node安裝文件夾里也只能看到'swiper/swiper-bundle.css'
如果用swiper-bundle.css會有很多問題,比如我遇到的就是分頁器不生效
這里就需要降低swiper版本了 我這里使用的是5.4.5

 

最終可用版本

 

 

 

下面代碼請放心食用

cnpm install vue-awesome-swiper swiper@5.4.5 --save
// 頁面代碼
<template>
    <div class="recommendPage">
        <swiper class="swiper" :options="swiperOption">
            <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>
            <swiper-slide>Slide 6</swiper-slide>
            <swiper-slide>Slide 7</swiper-slide>
            <swiper-slide>Slide 8</swiper-slide>
            <swiper-slide>Slide 9</swiper-slide>
            <swiper-slide>Slide 10</swiper-slide>
            <div class="swiper-pagination" slot="pagination"></div>
        </swiper>
    </div>
</template>

<script>
    import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
    import 'swiper/css/swiper.css'

    export default {
        name: 'swiper-example-pagination-dynamic',
        title: 'Pagination / Dynamic bullets',
        components: {
            Swiper,
            SwiperSlide
        },
        data() {
            return {
                swiperOption: {
                    autoplay: {
                        disableOnInteraction: false,
                    },
                    pagination: {
                        el: '.swiper-pagination',
                        dynamicBullets: true
                    }
                }
            }
        }
    }
</script>
<style scoped >
    .recommendPage .swiper-container{
        position: relative;
        width: 100%;
        height: 200px;
        background: pink;
    }
    .recommendPage .swiper-container .swiper-slide{
        width: 100%;
        line-height: 200px;
        background: yellowgreen;
        color: #000;
        font-size: 16px;
        text-align: center;
    }
</style>

 

 

用了以上代碼,一個基本的 swiper輪播實現應該沒問題了。

下面說一下點擊事件失效的問題:

 

在使用loop模式下 動態循環數據   點擊事件不起作用 ,

通過查看api  loop模式下會在slides前后復制若干個slide來實現的,

但是這個復制只是針對 dom 不會帶上事件的   所以不能在dom上 直接綁定事件   綁定則無效

 

解決方案:

先聲明個全局變量 vm 

 

 

 

在mounted鈎子里 讓vm = this ,這時vue 實例就指向了 vm 

 

 

下面我們就可以用  vm 來代替this ,找到data中的變量 或者 methods中的方法了

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM