swiper插件报错 vue_vue项目swiper插件的使用

step1.安装插件

cnpm install vue-awesome-swiper --save

step2.在当前页面引用插件

// 引入swiper的css样式

require('swiper/dist/css/swiper.css');

import Vue from "vue";

import VueAwesomeSwiper from 'vue-awesome-swiper';

Vue.use(VueAwesomeSwiper);

import { swiper, swiperSlide } from 'vue-awesome-swiper';

step3.组件声明

components: {

swiper,

swiperSlide,

},

step4.data数据声明

!!! notNextTick是一个组件自有属性,如果notNextTick设置为true,组件则不会通过NextTick来实例化swiper,也就意味着你可以在第一时间获取到swiper对象,假如你需要刚加载遍使用获取swiper对象来做什么事,那么这个属性一定要是true

data(){

return {

notNextTick: true,

swiperOption: {

// swiper optionss 所有的配置同swiper官方api配置

// autoplay: 3000,

direction: 'horizontal',

grabCursor: true,

setWrapperSize: true,

autoHeight: true,

pagination: '.swiper-pagination',

paginationClickable: true,

prevButton: '.swiper-button-prev',

nextButton: '.swiper-button-next',

// scrollbar: '.swiper-scrollbar',

mousewheelControl: true,

observeParents: true,

// if you need use plugins in the swiper, you can config in here like this

// 如果自行设计了插件,那么插件的一些配置相关参数,也应该出现在这个对象中,如下debugger

debugger: true,

// swiper callbacks

// swiper的各种回调函数也可以出现在这个对象中,和swiper官方一样

onTransitionStart(swiper){

console.log(swiper)

},

}

}}

step5.html标签结构

![](pic)

step6.调用swiper封装好的方法

添加swiper计算属性方法

// 如果你需要得到当前的swiper对象来做一些事情,你可以像下面这样定义一个方法属性来获取当前的swiper对象,同时notNextTick必须为true

computed: {

swiper:function() {

return this.$refs.mySwiper.swiper

},

},

在项目方法中调用swiper插件的封装方法(slideTo())

// 然后你就可以使用当前上下文内的swiper对象去做你想做的事了

methods:{

checkPic:function (index,picID) {

var self = this;

self.popupImgFlag = true;

self.photoArg = self.items[index].picUrl;

this.swiper.slideTo(picID, 1000, false); //slideTo()

document.body.style.overflowY = "hidden";

document.getElementById("app").style.overflowY = "hidden";

},

}

step7.修改分页器样式

在当前组件下,另外再创建要给style标签,且不用scoped限制作用域,再把要修改的分页器样式写在此style标签内。(过程中,直接在当前的style样式(有scoped限制)修改样式无效,遂通过搜索找到此方法)

....(在这里修改分页器样式无效)

//额外添加下述多一个style标签样式

#skinDetail .swiper-pagination-bullet{ //记得在其前面添加父级样式名(如#skinDetail),以避免影响全局样式

background-color: #fff;

}

#skinDetail .swiper-pagination-bullet-active{

background-color: #007aff;

}

项目过程遇到的坑:

在项目中,我的html结构内容是包含在一个块内,并通过v-if控制轮播的出现和消失,然而在点击出现内容时,页面轮播插件显示正常,而swiper方法却不可执行,console后台报错undefined,最后排查发现是计算属性computed在执行时,获取不到swiper对象,而后将v-if改为v-show即解决。(报错的原因:开始v-if为false,此时弹窗并未编译渲染到当前页面结构,因此computed执行时,并未找到swiper内容,所以执行方法this.swiper.slideTo()报错,这也从正面证明了v-if的初始化较快,但切换代价高;)

![](pic)

console报错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值