前言

滑动删除,在很多APP软件里面可以见到,比如淘宝的订单列表,QQ微信的聊天记录等等,今天就来看看JavaScript是如何实现这个功能的,之所以说是vue,主要是框架是vue啦,主要还是JS+CSS部分。

VUE开发一个组件——Vue list列表滑动删除

页面部分

页面就超级简单咯,遍历一个列表,添加touchstarttouchend事件,并添加删除按钮。如果滑动就添加move类样式,向左滑动60px

<ul> <li v-for="(item,index) in list" :class="{move:candelete.id==item.id}" @touchstart="touchStart(item)" @touchend="touchEnd(item)" > {{item.text}}{{item.id}} <div class="del" @click="deleteItem(index)">删除</div> </li> </ul>
li{ background: #fdfdfd; border-bottom: 1px solid #e1e1e1; line-height: 40px; position: relative; transform: translateX(0); transition: all .3s; /*滑动效果更生动*/ padding-left: 10px; } ul{ overflow-x: hidden; /*隐藏ul x轴的滚动条*/ } li.move { transform: translateX(-60px); /*滑动后x轴位移-60px,使其可见*/ } .del { position: absolute; top: 0; right: -1px; z-index: 3; width: 60px; height: 100%; text-align: center; color: #fff; background-color: #ff5b45; transform: translateX(60px); /*默认x轴位移60px,使其隐藏*/ }

data数据部分

data() { return { // 数据 list: [{ id: 1, text: '请左滑动删除我吧' },{ id: 2, text: '请左滑动删除我吧' },{ id: 3, text: '请左滑动删除我吧' },{ id: 4, text: '请左滑动删除我吧' },{ id: 5, text: '请左滑动删除我吧' },{ id: 6, text: '请左滑动删除我吧' }], clientNum: {}, // 记录开始滑动(x1),结束滑动(x2)的鼠标指针的位置 candelete: {}, // 滑动的item } }

事件部分

methods: { /** * 删除item * index是下标 */ deleteItem(index){ this.list.splice(index, 1) // splice方法是删除数组某条数据,或者向某个位置添加数据 }, touchStart(item) { let touchs = event.changedTouches[0]; // 记录开始滑动的鼠标位置 this.clientNum.x1 = touchs.pageX; this.candelete = {}; }, touchEnd(item) { let touchs = event.changedTouches[0]; // 记录结束滑动的鼠标位置 this.clientNum.x2 = touchs.pageX; this.candelete = {}; // 判断滑动距离大于50,判定为滑动成功,否则失败 if ( this.clientNum.x2 < this.clientNum.x1 && Math.abs(this.clientNum.x1) - Math.abs(this.clientNum.x2) > 50 ) { event.preventDefault(); this.candelete = item; } else if ( this.clientNum.x2 > this.clientNum.x1 && Math.abs(this.clientNum.x2) - Math.abs(this.clientNum.x1) > 10 ) { event.preventDefault(); this.candelete = {}; } } }

就这样愉快的结束了,是不是很简单了?

推荐文章

《ES6中Array数组你应该知道的操作》
《你对JavaScript的Array对象了解有多少?》
《CSS3中transition、transform傻傻分不清楚》