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;
         100%;
        height: 200px;
        background: pink;
    }
    .recommendPage .swiper-container .swiper-slide{
         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中的方法了

 

原文地址:https://www.cnblogs.com/listen9436/p/14960157.html