index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import { VantComponent } from '../common/component';
  2. import { touch } from '../mixins/touch';
  3. import { canIUseModel } from '../common/version';
  4. import { getRect } from '../common/utils';
  5. VantComponent({
  6. mixins: [touch],
  7. props: {
  8. disabled: Boolean,
  9. useButtonSlot: Boolean,
  10. activeColor: String,
  11. inactiveColor: String,
  12. max: {
  13. type: Number,
  14. value: 100,
  15. },
  16. min: {
  17. type: Number,
  18. value: 0,
  19. },
  20. step: {
  21. type: Number,
  22. value: 1,
  23. },
  24. value: {
  25. type: Number,
  26. value: 0,
  27. observer(val) {
  28. if (val !== this.value) {
  29. this.updateValue(val);
  30. }
  31. },
  32. },
  33. barHeight: null,
  34. },
  35. created() {
  36. this.updateValue(this.data.value);
  37. },
  38. methods: {
  39. onTouchStart(event) {
  40. if (this.data.disabled) return;
  41. this.touchStart(event);
  42. this.startValue = this.format(this.value);
  43. this.dragStatus = 'start';
  44. },
  45. onTouchMove(event) {
  46. if (this.data.disabled) return;
  47. if (this.dragStatus === 'start') {
  48. this.$emit('drag-start');
  49. }
  50. this.touchMove(event);
  51. this.dragStatus = 'draging';
  52. getRect(this, '.van-slider').then((rect) => {
  53. const diff = (this.deltaX / rect.width) * this.getRange();
  54. this.newValue = this.startValue + diff;
  55. this.updateValue(this.newValue, false, true);
  56. });
  57. },
  58. onTouchEnd() {
  59. if (this.data.disabled) return;
  60. if (this.dragStatus === 'draging') {
  61. this.updateValue(this.newValue, true);
  62. this.$emit('drag-end');
  63. }
  64. },
  65. onClick(event) {
  66. if (this.data.disabled) return;
  67. const { min } = this.data;
  68. getRect(this, '.van-slider').then((rect) => {
  69. const value =
  70. ((event.detail.x - rect.left) / rect.width) * this.getRange() + min;
  71. this.updateValue(value, true);
  72. });
  73. },
  74. updateValue(value, end, drag) {
  75. value = this.format(value);
  76. const { min } = this.data;
  77. const width = `${((value - min) * 100) / this.getRange()}%`;
  78. this.value = value;
  79. this.setData({
  80. barStyle: `
  81. width: ${width};
  82. ${drag ? 'transition: none;' : ''}
  83. `,
  84. });
  85. if (drag) {
  86. this.$emit('drag', { value });
  87. }
  88. if (end) {
  89. this.$emit('change', value);
  90. }
  91. if ((drag || end) && canIUseModel()) {
  92. this.setData({ value });
  93. }
  94. },
  95. getRange() {
  96. const { max, min } = this.data;
  97. return max - min;
  98. },
  99. format(value) {
  100. const { max, min, step } = this.data;
  101. return Math.round(Math.max(min, Math.min(value, max)) / step) * step;
  102. },
  103. },
  104. });