小程式 — 實現左滑刪除效果②
前言:這章我們為 movable-view 新增點選事件,完善左滑效果。
GitHub: ofollow,noindex">https://github.com/Ewall1106/miniProgramDemo
1、 拖動事件
(1)在上一章中,我們給 movable-view
綁定了一個 bindchange
事件,事件名為 onChange
,這個事件是幹嗎的呢?
拖動過程中觸發的事件,event.detail = {x: x, y: y, source: source},其中source表示產生移動的原因,值可為touch(拖動)、touch-out-of-bounds(超出移動範圍)、out-of-bounds(超出移動範圍後的回彈)、friction(慣性)和空字串(setData)

事件繫結
(2)所以我們就可以利用這個事件做點事情了
- 首先我們先定義三個初始化變數
x
、currentX
data = { // x軸方向的偏移 x: 0, // 當前x的值 currentX: 0 };
- 然後監聽下拖動事件並賦值給currentX
handleMovableChange(e) { this.currentX = e.detail.x; this.$apply(); }
2、手指觸控事件
將當前的 currentX
賦值給 x
以定義偏移量。
methods = { handleMovableChange(e) { this.currentX = e.detail.x; this.$apply(); }, handleTouchend(e) { if (this.currentX < -46) { this.x = -92; this.setData({ x: this.x }); } else { this.x = 0; this.setData({ x: this.x }); } } };
上面有幾行程式碼很少但卻是整個實現左滑刪除效果的核心程式碼, 請仔細看 ,這裡涉及到一個數據渲染的問題,後面我會講。
this.x = -92; this.setData({ x: this.x });
3、完整程式碼
全部js程式碼:
<script> import wepy from 'wepy'; export default class Chapter5 extends wepy.page { data = { // x軸方向的偏移 x: 0, // 當前x的值 currentX: 0 }; methods = { handleMovableChange(e) { this.currentX = e.detail.x; this.$apply(); }, handleTouchend(e) { if (this.currentX < -46) { this.x = -92; this.setData({ x: this.x }); } else { this.x = 0; this.setData({ x: this.x }); } } }; } </script>
至此,我們的用小程式實現左滑刪除的效果基本上就全部實現了,如果你是用小程式原生開發的話,其實原理都是一樣的,所以實現的方式也差不多。下一章是進階。