微信小程序左滑删除自定义组件

slider-componets.wxml

<view class="container" >
  <view class="slide-box"
        style="transform: translateX(-{{translateX}}rpx);transition: transform .8s "
        bindtouchstart="handleTouchStart"
        bindtouchmove="handleTouchMove"
        bindtouchend="handleTouchEnd"
  >
    <view class="slide-left" >
      <slot name="slideLeft">slot>
    view>
    <view class="slide-right" style="width:{{slideWidth}}rpx">
      <slot name="slideRight">slot>
    view>
  view>
view>

slider-componets.js

Component({
	options: {
		multipleSlots: true,
	},
	properties: {
		slideWidth: { // 右侧滑块的width
			type: Number,
			value: 0,
		},
	},
	data: {scroll: true, touches: [], translateX: 0},
	methods: {
		/* 计算滑动角度
		* @param {Object} start 起点坐标
		* @param {Object} end 终点坐标
		*/
		handleAngle(start, end) {
			var _X = end.clientX - start.clientX;
			var _Y = end.clientY - start.clientY;
			// 返回角度 /Math.atan()返回数字的反正切值
			return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
		},
		// 触摸开始
		handleTouchStart(e) {
			const {touches} = e;
			// @touches typeof  Array
			// touches.length  手指触摸屏幕的个数
			this.data.scroll = touches.length === 1;
			this.data.touches = e.touches;
		},
		handleTouchMove(e) {
			if (this.data.scroll) {
				// 滑滑动的角度
				let angle = this.handleAngle(this.data.touches[0], e.touches[0]);
				// 滑滑动的角度 如果 > 30 不做操作
				if (Math.abs(angle) > 40) return;
				// PosX 手指在X轴的坐标差   判断滑动方向
				let PosX = e.touches[0].pageX - this.data.touches[0].pageX;
				// PosX < -50  => Left  左滑
				// PosX > 50  => Right 右滑
				if (PosX < -50) {
					this.setData({
						translateX: this.properties.slideWidth,
					});
				}
				else if (PosX > 50) {
					this.setData({
						translateX: 0,
					});
				}
			}
		},

		// 触摸结束
		handleTouchEnd(e) {
			this.data.scroll = false;
		},
	},
	pageLifetimes: {
		// 组件所在页面的生命周期函数
		hide: function () {
			this.setData({
				translateX: 0,
			});
		},
	},
});

wxs

.container{
  position: relative;
  padding: 0;
  overflow: hidden;
}
  

.container  .slide-box{
	 position: relative;
    min-height: 40rpx;
}
   

.slide-right{
	 position: absolute;
	 top: 0;
     bottom: 0;
     left: 100%;

}
     

slider-componets.json

{
	"component": true
}

你可能感兴趣的:(微信小程序)