index.vue 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <template>
  2. <view class="nut-range-container">
  3. <view class="min" v-if="!hiddenRange">{{ +min }}</view>
  4. <view
  5. ref="root"
  6. :style="wrapperStyle"
  7. :class="classes"
  8. @click.stop="onClick"
  9. >
  10. <view class="nut-range-bar" :style="barStyle">
  11. <template v-if="range">
  12. <view
  13. v-for="index of [0, 1]"
  14. :key="index"
  15. role="slider"
  16. :class="{
  17. 'nut-range-button-wrapper-left': index == 0,
  18. 'nut-range-button-wrapper-right': index == 1
  19. }"
  20. :tabindex="disabled ? -1 : 0"
  21. :aria-valuemin="+min"
  22. :aria-valuenow="curValue(index)"
  23. :aria-valuemax="+max"
  24. aria-orientation="horizontal"
  25. @touchstart.stop.prevent="
  26. e => {
  27. if (typeof index === 'number') {
  28. // 实时更新当前拖动的按钮索引
  29. buttonIndex = index;
  30. }
  31. onTouchStart(e);
  32. }
  33. "
  34. @touchmove.stop.prevent="onTouchMove"
  35. @touchend.stop.prevent="onTouchEnd"
  36. @touchcancel.stop.prevent="onTouchEnd"
  37. @click="e => e.stopPropagation()"
  38. >
  39. <slot v-if="$slots.button" name="button"></slot>
  40. <view class="nut-range-button" v-else :style="buttonStyle">
  41. <view class="number" v-if="!hiddenTag">{{
  42. curValue(index)
  43. }}</view>
  44. </view>
  45. </view>
  46. </template>
  47. <template v-else>
  48. <view
  49. role="slider"
  50. class="nut-range-button-wrapper"
  51. :tabindex="disabled ? -1 : 0"
  52. :aria-valuemin="+min"
  53. :aria-valuenow="curValue()"
  54. :aria-valuemax="+max"
  55. aria-orientation="horizontal"
  56. @touchstart.stop.prevent="
  57. e => {
  58. onTouchStart(e);
  59. }
  60. "
  61. @touchmove.stop.prevent="onTouchMove"
  62. @touchend.stop.prevent="onTouchEnd"
  63. @touchcancel.stop.prevent="onTouchEnd"
  64. @click="e => e.stopPropagation()"
  65. >
  66. <slot v-if="$slots.button" name="button"></slot>
  67. <view class="nut-range-button" v-else :style="buttonStyle">
  68. <view class="number" v-if="!hiddenTag">{{
  69. curValue(index)
  70. }}</view>
  71. </view>
  72. </view>
  73. </template>
  74. </view>
  75. </view>
  76. <view class="max" v-if="!hiddenRange">{{ +max }}</view>
  77. </view>
  78. </template>
  79. <script lang="ts">
  80. import { ref, toRefs, computed, PropType, CSSProperties } from 'vue';
  81. import { createComponent } from '@/utils/create';
  82. import { useTouch } from '@/utils/useTouch';
  83. import { useRect } from '@/utils/useRect';
  84. const { componentName, create } = createComponent('range');
  85. type SliderValue = number | number[];
  86. export default create({
  87. props: {
  88. range: {
  89. type: Boolean,
  90. default: false
  91. },
  92. disabled: Boolean,
  93. activeColor: String,
  94. inactiveColor: String,
  95. buttonColor: String,
  96. hiddenRange: {
  97. type: Boolean,
  98. default: false
  99. },
  100. hiddenTag: {
  101. type: Boolean,
  102. default: false
  103. },
  104. min: {
  105. type: [Number, String],
  106. default: 0
  107. },
  108. max: {
  109. type: [Number, String],
  110. default: 100
  111. },
  112. step: {
  113. type: [Number, String],
  114. default: 1
  115. },
  116. modelValue: {
  117. type: [Number, Array] as PropType<SliderValue>,
  118. default: 0
  119. }
  120. },
  121. components: {},
  122. emits: ['change', 'drag-end', 'drag-start', 'update:modelValue'],
  123. setup(props, { emit, slots }) {
  124. console.log(slots.button && slots.button());
  125. const buttonIndex = ref(0);
  126. let startValue: SliderValue;
  127. let currentValue: SliderValue;
  128. const root = ref<HTMLElement>();
  129. const dragStatus = ref<'start' | 'draging' | ''>();
  130. const touch = useTouch();
  131. // 滑动范围计算
  132. const scope = computed(() => Number(props.max) - Number(props.min));
  133. const classes = computed(() => {
  134. const prefixCls = componentName;
  135. return {
  136. [prefixCls]: true,
  137. [`${prefixCls}-disabled`]: props.disabled,
  138. [`${prefixCls}-show-number`]: !props.hiddenRange
  139. };
  140. });
  141. // 滑轨样式
  142. const wrapperStyle = computed(() => {
  143. return {
  144. background: props.inactiveColor
  145. };
  146. });
  147. // 按钮样式
  148. const buttonStyle = computed(() => {
  149. return {
  150. borderColor: props.buttonColor
  151. };
  152. });
  153. // 判断是否是双滑块
  154. const isRange = (val: unknown): val is number[] =>
  155. !!props.range && Array.isArray(val);
  156. // 组件核心:拖动效果主要是通过计算选中条长度百分比、开始位置偏移量来实现
  157. // 计算选中条的长度百分比
  158. const calcMainAxis = () => {
  159. const { modelValue, min } = props;
  160. // 双滑块时,拖动滑块,通过实时变化滑动条的宽度,间接让滑块移动
  161. // 如果拖动右滑块,则只会改变滑动条的宽度,开始位置偏移量不会变化
  162. if (isRange(modelValue)) {
  163. return `${((modelValue[1] - modelValue[0]) * 100) / scope.value}%`;
  164. }
  165. // 单滑块时,通过实时变化滑动条宽度,来让滑块移动
  166. return `${((modelValue - Number(min)) * 100) / scope.value}%`;
  167. };
  168. // 计算选中条的开始位置的偏移量
  169. const calcOffset = () => {
  170. const { modelValue, min } = props;
  171. // 双滑块时,如果拖动左滑块,则不仅会改变滑动条宽度,还要改变滑动条的开始位置
  172. if (isRange(modelValue)) {
  173. return `${((modelValue[0] - Number(min)) * 100) / scope.value}%`;
  174. }
  175. // 单滑块时,开始位置永远是最左侧
  176. return `0%`;
  177. };
  178. // 选中条样式
  179. const barStyle = computed<CSSProperties>(() => {
  180. return {
  181. width: calcMainAxis(),
  182. left: calcOffset(),
  183. background: props.activeColor,
  184. transition: dragStatus.value ? 'none' : undefined
  185. };
  186. });
  187. const format = (value: number) => {
  188. const { min, max, step } = props;
  189. value = Math.max(+min, Math.min(value, +max)); // 拖动范围限制
  190. return Math.round(value / +step) * +step; // 每一步四舍五入
  191. };
  192. const isSameValue = (newValue: SliderValue, oldValue: SliderValue) =>
  193. JSON.stringify(newValue) === JSON.stringify(oldValue);
  194. // 处理两个滑块交错之后的情况
  195. // 例如左滑块移动到右滑块右边,这个时候需要将两个滑块值进行交换
  196. const handleOverlap = (value: number[]) => {
  197. if (value[0] > value[1]) {
  198. return value.slice(0).reverse();
  199. }
  200. return value;
  201. };
  202. const updateValue = (value: SliderValue, end?: boolean) => {
  203. if (isRange(value)) {
  204. value = handleOverlap(value).map(format);
  205. } else {
  206. value = format(value);
  207. }
  208. if (!isSameValue(value, props.modelValue)) {
  209. emit('update:modelValue', value);
  210. }
  211. if (end && !isSameValue(value, startValue)) {
  212. emit('change', value);
  213. }
  214. };
  215. const onClick = (event: MouseEvent) => {
  216. if (props.disabled) {
  217. return;
  218. }
  219. const { min, modelValue } = props;
  220. const rect = useRect(root);
  221. const delta = event.clientX - rect.left;
  222. const total = rect.width;
  223. const value = Number(min) + (delta / total) * scope.value;
  224. if (isRange(modelValue)) {
  225. const [left, right] = modelValue;
  226. const middle = (left + right) / 2;
  227. // 靠左边点击移动左按钮,靠右边点击移动右按钮
  228. if (value <= middle) {
  229. updateValue([value, right], true);
  230. } else {
  231. updateValue([left, value], true);
  232. }
  233. } else {
  234. updateValue(value, true);
  235. }
  236. };
  237. const onTouchStart = (event: TouchEvent) => {
  238. if (props.disabled) {
  239. return;
  240. }
  241. touch.start(event);
  242. currentValue = props.modelValue;
  243. if (isRange(currentValue)) {
  244. startValue = currentValue.map(format);
  245. } else {
  246. startValue = format(currentValue);
  247. }
  248. dragStatus.value = 'start';
  249. };
  250. const onTouchMove = (event: TouchEvent) => {
  251. if (props.disabled) {
  252. return;
  253. }
  254. if (dragStatus.value === 'start') {
  255. emit('drag-start');
  256. }
  257. touch.move(event);
  258. dragStatus.value = 'draging';
  259. const rect = useRect(root);
  260. const delta = touch.deltaX.value;
  261. const total = rect.width;
  262. const diff = (delta / total) * scope.value;
  263. if (isRange(startValue)) {
  264. (currentValue as number[])[buttonIndex.value] =
  265. startValue[buttonIndex.value] + diff;
  266. } else {
  267. currentValue = startValue + diff;
  268. }
  269. updateValue(currentValue);
  270. };
  271. const onTouchEnd = () => {
  272. if (props.disabled) {
  273. return;
  274. }
  275. if (dragStatus.value === 'draging') {
  276. updateValue(currentValue, true);
  277. emit('drag-end');
  278. }
  279. dragStatus.value = '';
  280. };
  281. const curValue = (idx?) => {
  282. const value =
  283. typeof idx === 'number'
  284. ? (props.modelValue as number[])[idx]
  285. : (props.modelValue as number);
  286. return value;
  287. };
  288. return {
  289. root,
  290. classes,
  291. wrapperStyle,
  292. buttonStyle,
  293. onClick,
  294. onTouchStart,
  295. onTouchMove,
  296. onTouchEnd,
  297. ...toRefs(props),
  298. barStyle,
  299. curValue,
  300. buttonIndex
  301. };
  302. }
  303. });
  304. </script>
  305. <style lang="scss">
  306. @import 'index.scss';
  307. </style>