index.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import { VantComponent } from '../common/component';
  2. import { touch } from '../mixins/touch';
  3. import { addUnit } from '../common/utils';
  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(value) {
  27. this.updateValue(value, false);
  28. }
  29. },
  30. barHeight: {
  31. type: null,
  32. value: '2px'
  33. }
  34. },
  35. created() {
  36. this.updateValue(this.data.value);
  37. },
  38. methods: {
  39. onTouchStart(event) {
  40. if (this.data.disabled)
  41. return;
  42. this.touchStart(event);
  43. this.startValue = this.format(this.data.value);
  44. this.dragStatus = 'start';
  45. },
  46. onTouchMove(event) {
  47. if (this.data.disabled)
  48. 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)
  62. return;
  63. if (this.dragStatus === 'draging') {
  64. this.updateValue(this.newValue, true);
  65. this.$emit('drag-end');
  66. }
  67. },
  68. onClick(event) {
  69. if (this.data.disabled)
  70. return;
  71. const { min } = this.data;
  72. this.getRect('.van-slider').then((rect) => {
  73. const value = ((event.detail.x - rect.left) / rect.width) * this.getRange() + min;
  74. this.updateValue(value, true);
  75. });
  76. },
  77. updateValue(value, end, drag) {
  78. value = this.format(value);
  79. const { barHeight, min } = this.data;
  80. const width = `${((value - min) * 100) / this.getRange()}%`;
  81. this.setData({
  82. value,
  83. barStyle: `
  84. width: ${width};
  85. height: ${addUnit(barHeight)};
  86. ${drag ? 'transition: none;' : ''}
  87. `,
  88. });
  89. if (drag) {
  90. this.$emit('drag', { value });
  91. }
  92. if (end) {
  93. this.$emit('change', value);
  94. }
  95. },
  96. getRange() {
  97. const { max, min } = this.data;
  98. return max - min;
  99. },
  100. format(value) {
  101. const { max, min, step } = this.data;
  102. return Math.round(Math.max(min, Math.min(value, max)) / step) * step;
  103. }
  104. }
  105. });