刘嘉威
2023-07-10 d3322ffc8cfbef45122784037eea48900f02f469
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
<script setup lang="ts">
import {
  computed,
  defineComponent,
  onBeforeMount,
  onMounted,
  ref,
  watch,
  nextTick,
} from "vue";
import type { CSSProperties } from "vue";
import throttle from "lodash/throttle";
type propsType = {
  modelValue?: boolean;
  list: Array<any>;
  step?: number;
  limitScrollNum?: number;
  hover?: boolean;
  direction?: string;
  singleHeight?: number;
  singleWidth?: number;
  singleWaitTime?: number;
  isRemUnit?: boolean;
  isWatch?: boolean;
  delay?: number;
  ease?: any;
  count?: number;
  copyNum?: number;
  wheel?: boolean;
  singleLine?: boolean;
};
const props = withDefaults(defineProps<propsType>(), {
  // 是否开启自动滚动
  modelValue: true,
  // 原始数据列表
  list: () => [],
  // 步进速度,step 需是单步大小的约数
  step: 1,
  // 开启滚动的数据量
  limitScrollNum: 3,
  // 是否开启鼠标悬停
  hover: false,
  // 控制滚动方向
  direction: "up",
  // 单步运动停止的高度
  singleHeight: 0,
  // 单步运动停止的宽度
  singleWidth: 0,
  // 单步停止等待时间 (默认值 1000ms)
  singleWaitTime: 1000,
  // 是否开启 rem 度量
  isRemUnit: false,
  // 开启数据更新监听
  isWatch: true,
  // 动画时间
  delay: 0,
  // 动画方式
  ease: "ease-in",
  // 动画循环次数,-1 表示一直动画
  count: -1,
  // 拷贝几份滚动列表
  copyNum: 1,
  // 开启鼠标悬停时支持滚轮滚动
  wheel: false,
  // 启用单行滚动
  singleLine: false,
});
interface Emits {
  (event: "count", _count: number): void;
  (event: "stop", _count: number): void;
}
const emit = defineEmits<Emits>();
const scrollRef = ref(null);
const slotListRef = ref<HTMLDivElement | null>(null);
const realBoxRef = ref<HTMLDivElement | null>(null);
const reqFrame = ref<number | null>(null);
const singleWaitTimeout = ref<TimeProp | null>(null);
const realBoxWidth = ref(0);
const realBoxHeight = ref(0);
const xPos = ref(0);
const yPos = ref(0);
const isHover = ref(false);
const _count = ref(0);
const isScroll = computed(() =>
  props.list ? props.list.length >= props.limitScrollNum : false
);
const realBoxStyle = computed(() => {
  return {
    width: realBoxWidth.value ? `${realBoxWidth.value}px` : "auto",
    transform: `translate(${xPos.value}px,${yPos.value}px)`,
    transition: `all ${
      typeof props.ease === "string"
        ? props.ease
        : "cubic-bezier(" +
          props.ease.x1 +
          "," +
          props.ease.y1 +
          "," +
          props.ease.x2 +
          "," +
          props.ease.y2 +
          ")"
    } ${props.delay}ms`,
    overflow: "hidden",
    display: props.singleLine ? "flex" : "block",
  };
});
const isHorizontal = computed(
  () => props.direction == "left" || props.direction == "right"
);
 
function dataWarm(list: any) {
  if (list && typeof list !== "boolean" && list.length > 100) {
    console.warn(
      `数据达到了${list.length}条有点多哦~,可能会造成部分老旧浏览器卡顿。`
    );
  }
}
const floatStyle = computed<CSSProperties>(() => {
  return isHorizontal.value
    ? {
        float: "left",
        overflow: "hidden",
        display: props.singleLine ? "flex" : "block",
        flexShrink: props.singleLine ? 0 : 1,
      }
    : { overflow: "hidden" };
});
const baseFontSize = computed(() => {
  return props.isRemUnit
    ? parseInt(
        globalThis.window.getComputedStyle(
          globalThis.document.documentElement,
          null
        ).fontSize
      )
    : 1;
});
const realSingleStopWidth = computed(
  () => props.singleWidth * baseFontSize.value
);
 
const realSingleStopHeight = computed(
  () => props.singleHeight * baseFontSize.value
);
 
const step = computed(() => {
  let singleStep: number;
  let _step = props.step;
  if (isHorizontal.value) {
    singleStep = realSingleStopWidth.value;
  } else {
    singleStep = realSingleStopHeight.value;
  }
  if (singleStep > 0 && singleStep % _step > 0) {
    console.error(
      "如果设置了单步滚动,step 需是单步大小的约数,否则无法保证单步滚动结束的位置是否准确。~~~~~"
    );
  }
  return _step;
});
 
const cancle = () => {
  cancelAnimationFrame(reqFrame.value as number);
  reqFrame.value = null;
};
const animation = (
  _direction: "up" | "down" | "left" | "right",
  _step: number,
  isWheel?: boolean
) => {
  // console.log("animation",_direction,_step,isWheel);
  reqFrame.value = requestAnimationFrame(function () {
    const h = realBoxHeight.value / 2;
    const w = realBoxWidth.value / 2;
    if (_direction === "up") {
      if (Math.abs(yPos.value) >= h) {
        yPos.value = 0;
        _count.value += 1;
        emit("count", _count.value);
      }
      yPos.value -= _step;
    } else if (_direction === "down") {
      if (yPos.value >= 0) {
        yPos.value = h * -1;
        _count.value += 1;
        emit("count", _count.value);
      }
      yPos.value += _step;
    } else if (_direction === "left") {
      if (Math.abs(xPos.value) >= w) {
        xPos.value = 0;
        _count.value += 1;
        emit("count", _count.value);
      }
      xPos.value -= _step;
    } else if (_direction === "right") {
      if (xPos.value >= 0) {
        xPos.value = w * -1;
        _count.value += 1;
        emit("count", _count.value);
      }
      xPos.value += _step;
    }
    if (isWheel) {
      return;
    }
    let { singleWaitTime } = props;
    if (singleWaitTimeout.value) {
      clearTimeout(singleWaitTimeout.value);
    }
    if (!!realSingleStopHeight.value) {
      if (Math.abs(yPos.value) % realSingleStopHeight.value < _step) {
        singleWaitTimeout.value = setTimeout(() => {
          move();
        }, singleWaitTime);
      } else {
        move();
      }
    } else if (!!realSingleStopWidth.value) {
      if (Math.abs(xPos.value) % realSingleStopWidth.value < _step) {
        singleWaitTimeout.value = setTimeout(() => {
          move();
        }, singleWaitTime);
      } else {
        move();
      }
    } else {
      move();
    }
  });
};
const move = () => {
  cancle();
  if (isHover.value || !isScroll.value || _count.value === props.count) {
    emit("stop", _count.value);
    _count.value = 0;
    return;
  }
  animation(
    props.direction as "up" | "down" | "left" | "right",
    step.value,
    false
  );
};
const initMove = () => {
  dataWarm(props.list);
  if (isHorizontal.value) {
    let slotListWidth = (slotListRef.value as HTMLDivElement).offsetWidth;
    slotListWidth = slotListWidth * 2 + 1;
    realBoxWidth.value = slotListWidth;
  }
  if (isScroll.value) {
    realBoxHeight.value = (realBoxRef.value as HTMLDivElement).offsetHeight;
    if (props.modelValue) {
      move();
    }
  } else {
    cancle();
    yPos.value = xPos.value = 0;
  }
  // console.log("initMove","isHorizontal",isHorizontal.value,"isScroll",isScroll.value,realBoxRef.value?.offsetHeight);
};
const startMove = () => {
  isHover.value = false;
  move();
};
 
const stopMove = () => {
  isHover.value = true;
  if (singleWaitTimeout.value) {
    clearTimeout(singleWaitTimeout.value);
  }
  cancle();
};
 
const hoverStop = computed(
  () => props.hover && props.modelValue && isScroll.value
);
const throttleFunc = throttle((e: WheelEvent) => {
  cancle();
  const singleHeight = !!realSingleStopHeight.value
    ? realSingleStopHeight.value
    : 15;
  if (e.deltaY < 0) {
    animation("down", singleHeight, true);
  }
  if (e.deltaY > 0) {
    animation("up", singleHeight, true);
  }
}, 30);
 
const onWheel = (e: WheelEvent) => {
  throttleFunc(e);
};
const reset = () => {
  cancle();
  isHover.value = false;
  initMove();
};
const Reset = () => {
  reset();
};
defineExpose({
  Reset,
});
 
watch(
  () => props.list,
  () => {
    if (props.isWatch) {
      nextTick(() => {
        reset();
      });
    }
  },
  {
    deep: true,
  }
);
 
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue) {
      startMove();
    } else {
      stopMove();
    }
  }
);
 
watch(
  () => props.count,
  (newValue) => {
    if (newValue !== 0) {
      startMove();
    }
  }
);
 
onBeforeMount(() => {
  cancle();
  clearTimeout(singleWaitTimeout.value as unknown as number);
});
 
onMounted(() => {
  if (isScroll.value) {
    initMove();
  }
});
</script>
 
<template>
  <div
    v-if="props.wheel && props.hover"
    ref="realBoxRef"
    :style="realBoxStyle"
    @mouseenter="
      () => {
        hoverStop && stopMove();
      }
    "
    @mouseleave="
      () => {
        hoverStop && startMove();
      }
    "
    @wheel="
      (e) => {
        hoverStop && onWheel(e);
      }
    "
  >
    <div ref="slotListRef" :style="floatStyle">
      <slot></slot>
    </div>
    <div :style="floatStyle">
      <slot></slot>
    </div>
  </div>
 
  <div
    v-else
    :style="realBoxStyle"
    ref="realBoxRef"
    @mouseenter="
      () => {
        hoverStop && stopMove();
      }
    "
    @mouseleave="
      () => {
        hoverStop && startMove();
      }
    "
  >
    <div ref="slotListRef" :style="floatStyle">
      <slot></slot>
    </div>
    <div :style="floatStyle">
      <slot></slot>
    </div>
  </div>
</template>
 
<style scoped lang="scss"></style>