index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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: 'updateValue',
  27. },
  28. barHeight: {
  29. type: null,
  30. value: '2px',
  31. },
  32. },
  33. created() {
  34. this.updateValue(this.data.value);
  35. },
  36. methods: {
  37. onTouchStart(event) {
  38. if (this.data.disabled) return;
  39. this.touchStart(event);
  40. this.startValue = this.format(this.data.value);
  41. this.dragStatus = 'start';
  42. },
  43. onTouchMove(event) {
  44. if (this.data.disabled) return;
  45. if (this.dragStatus === 'start') {
  46. this.$emit('drag-start');
  47. }
  48. this.touchMove(event);
  49. this.dragStatus = 'draging';
  50. this.getRect('.van-slider').then((rect) => {
  51. const diff = (this.deltaX / rect.width) * 100;
  52. this.newValue = this.startValue + diff;
  53. this.updateValue(this.newValue, false, true);
  54. });
  55. },
  56. onTouchEnd() {
  57. if (this.data.disabled) return;
  58. if (this.dragStatus === 'draging') {
  59. this.updateValue(this.newValue, true);
  60. this.$emit('drag-end');
  61. }
  62. },
  63. onClick(event) {
  64. if (this.data.disabled) return;
  65. const { min } = this.data;
  66. this.getRect('.van-slider').then((rect) => {
  67. const value =
  68. ((event.detail.x - rect.left) / rect.width) * this.getRange() + min;
  69. this.updateValue(value, true);
  70. });
  71. },
  72. updateValue(value, end, drag) {
  73. value = this.format(value);
  74. const { min } = this.data;
  75. const width = `${((value - min) * 100) / this.getRange()}%`;
  76. this.setData({
  77. value,
  78. barStyle: `
  79. width: ${width};
  80. ${drag ? 'transition: none;' : ''}
  81. `,
  82. });
  83. if (drag) {
  84. this.$emit('drag', { value });
  85. }
  86. if (end) {
  87. this.$emit('change', value);
  88. }
  89. if ((drag || end) && canIUseModel()) {
  90. this.setData({ value });
  91. }
  92. },
  93. getRange() {
  94. const { max, min } = this.data;
  95. return max - min;
  96. },
  97. format(value) {
  98. const { max, min, step } = this.data;
  99. return Math.round(Math.max(min, Math.min(value, max)) / step) * step;
  100. },
  101. },
  102. });