index.js 2.6 KB

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