index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * @description: 小程序左划删除组件
  3. * @Author: bigmeow (https://github.com/bigmeow/minapp-slider-left)
  4. */
  5. 'use strict'
  6. Object.defineProperty(exports, '__esModule', {
  7. value: true
  8. });
  9. exports.default = Component({
  10. properties: {
  11. // 组件的可视宽度设置(rpx)
  12. width: {
  13. type: Number,
  14. value: 750,
  15. },
  16. // 阈值,往左移动超过则显示菜单项,否则隐藏(一般为菜单宽的40%)
  17. moveThreshold: {
  18. type: Number,
  19. value: 30
  20. },
  21. // 可以往左拖动的最大距离,同时它也是组件的初始x坐标,此时菜单不可见
  22. openWidth: {
  23. type: Number,
  24. value: 90
  25. },
  26. // 菜单是否打开了,true表示打开,false表示关闭
  27. open: {
  28. type: Boolean,
  29. value: false,
  30. observer: function (open) {
  31. this.setData({
  32. x: open ? 0 : this.data.openWidth
  33. })
  34. this.triggerEvent('change', {
  35. open
  36. })
  37. }
  38. }
  39. },
  40. /**
  41. * 组件的初始数据
  42. */
  43. data: {
  44. x: 75, // 单位px
  45. currentX: 75, // 当前记录组件被拖动时的x坐标
  46. moveInstance: 0 // 记录往左移动的距离
  47. },
  48. attached: function () {
  49. this.setData({
  50. x: this.data.open ? 0 : this.data.openWidth
  51. })
  52. },
  53. methods: {
  54. handleChange: function (e) {
  55. const x = e.detail.x
  56. this.data.moveInstance = this.data.openWidth - x
  57. this.data.currentX = x
  58. // console.log(this.data.moveInstance)
  59. },
  60. handleTouchend: function () {
  61. // 如果松开手指的时候,已经被拖拽到最左边或者最右边,则不处理
  62. if (this.data.currentX === 0) {
  63. this.setData({ open: true })
  64. return
  65. }
  66. if (this.data.currentX === this.data.openWidth) {
  67. this.setData({ open: false })
  68. return
  69. }
  70. // 如果当前菜单是打开的,只要往右移动的距离大于0就马上关闭菜单
  71. if (this.data.open && this.data.currentX > 0) {
  72. this.setData({ open: false })
  73. return
  74. }
  75. // 如果当前菜单是关着的,只要往左移动超过阀值就马上打开菜单
  76. if (this.data.moveInstance < this.data.moveThreshold) {
  77. this.setData({
  78. open: false,
  79. x: this.data.openWidth
  80. })
  81. } else {
  82. this.setData({ open: true })
  83. }
  84. },
  85. // 点击删除按钮触发的事件
  86. handleDelete: function () {
  87. this.setData({ open: false })
  88. this.triggerEvent('delete')
  89. },
  90. // 开始左滑时触发(轻触摸的时候也会触发),主要用于显示当前删除按钮前先 隐藏掉其它项的删除按钮
  91. handleTouchestart: function () {
  92. if (!this.data.open) {
  93. this.triggerEvent('sliderLeftStart')
  94. }
  95. }
  96. }
  97. })