index.js 3.0 KB

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