温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用vue+swiper实现一个左右滑动的测试题功能

发布时间:2020-11-02 15:47:20 来源:亿速云 阅读:289 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关使用vue+swiper实现一个左右滑动的测试题功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

我用了vue和swiper。所有的题目是一个对象数组,通过v-for渲染:

<swiper ref="mySwiper" :options="swiperOptions">
 <swiper-slide v-for="(item, index) in listData" :key="index">
  <div class="question-box">
   <div class="idx">- 第{{ index+1 }}题 -</div>
   <div class="question">{{ item.question }}</div>
  </div>
  <button @click="goNext(index, 'a')" :class="item.answer=='a' &#63; 'active': ''">是</button>
  <button @click="goNext(index, 'b')" :class="item.answer=='b' &#63; 'active': ''">否</button>
 </swiper-slide>
</swiper>

一开始我把每道题目的answer存放在对象里面,点击的按钮时候切换answer的值,button的动态class监听到值改变后会引发背景色的改变。js部分:

goNext(index, answer) {
 this.$set(this.listData[index], 'answer', answer)
 this.swiper.slideNext(100)
},

发现问题

测试发现这样把点击事件和动态样式互相依赖,会造成大概几百毫秒的延迟才执行slideNext(),是可以直观感受到的延迟。通过调试,发现造成延迟有两方面的原因:

  • this.$set 更改数组
  • 执行完点击事件动态class监听到数据的改变 中间也有延迟。

于是我换了一个思路,不把每个题目的answer放在对像数组里面,而是在data里面定义一个answerMap,这样解决了问题1。为了解决问题2,我选择把动态样式 :class 去掉,改成用原生js在点击事件里面直接修改class。这样两步下来,确实看不到延迟了。

优化后的代码

html部分

<button @click="goNext($event, index, 'a')">是</button>
<button @click="goNext($event, index, 'b')">否</button>

js部分

goNext(e, index, answer) {
 const element = e.target
 const bro = element.parentNode.children
 for (let i = 0; i < bro.length; i++) {
  if (bro[i] !== element) {
   bro[i].classList.remove("active")
  }
 }
 element.classList.add('active')
 this.answerMap[this.listData[index].question] = answer
 this.swiper.slideNext(100)
},

以上就是使用vue+swiper实现一个左右滑动的测试题功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI