如何封装一个可复用的滑动组件(如 Swipeable)?

解读

国内面试官问“封装可复用滑动组件”时,重点不在“能滑”,而在“能稳、能快、能插、能测”。
稳:边界处理、内存泄漏、事件清理;快:GPU 加速、节流、Passive 事件;插:Vue 插槽、v-model、自定义指令、TypeScript 声明;测:单元测试、E2E、真机。
回答必须体现“渐进式”思想:核心逻辑与框架解耦,再包一层 Vue 外衣,方便渐进接入老项目,也方便未来迁移。

知识点

  1. 手势数学:touchstart → touchmove → touchend 三角函数求速、方向锁、阈值。
  2. 渲染优化:transform3d 硬件加速、will-change、requestAnimationFrame 节流。
  3. 组件设计:
    • props 接口:list、initialIndex、loop、threshold、duration、autoplay。
    • 事件:@change、@slide-start、@slide-end。
    • v-model:index 语法糖。
  4. 组合式 API:useSwipe、useAutoPlay、useLoop,逻辑拆分,方便 tree-shaking。
  5. 内存管理:passive 事件、removeEventListener、onScopeDispose。
  6. SSR 安全:typeof window !== 'undefined' 判断;服务端预渲染首屏兜底。
  7. 测试:@vue/test-utils + jsdom-touch-event + Vitest 单元;Cypress 真机滑动 E2E。
  8. 无障碍:aria-label、role="tabpanel"、键盘 ← → 操作。
  9. 微前端:导出 defineCustomElement,让 React/Angular 老项目直接 <swipeable-ce> 使用。

答案

下面给出一个“能直接写白板”的精简版,兼顾核心思路与可扩展性。
(面试官若追问细节,可再把“节流系数、边界回弹、GPU 层”逐层展开。)

// Swipeable.vue
<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'

interface Props {
  list: any[]
  initialIndex?: number
  threshold?: number      // 滑动多少 px 算翻页
  duration?: number       // 动画 ms
  loop?: boolean
  autoplay?: number       // ms,0 表示关闭
}
const props = withDefaults(defineProps<Props>(), {
  initialIndex: 0,
  threshold: 50,
  duration: 300,
  loop: true,
  autoplay: 3000
})
const emit = defineEmits<{
  change: [index: number]
  'update:index': [index: number]
}>()

const current = ref(props.initialIndex)
const container = ref<HTMLElement>()
let startX = 0
let startY = 0
let deltaX = 0
let locked = false
let timer: number | null = null

const total = computed(() => props.list.length)

/* 无限循环:把真实索引映射到 0~total-1 */
const safeIndex = (i: number) => {
  if (!props.loop) return Math.max(0, Math.min(i, total.value - 1))
  return (i + total.value) % total.value
}

const go = (i: number, isSilent = false) => {
  const next = safeIndex(i)
  current.value = next
  if (!isSilent) {
    emit('change', next)
    emit('update:index', next)
  }
}

/* 自动播放 */
const resetTimer = () => {
  if (timer) window.clearInterval(timer)
  if (props.autoplay > 0) {
    timer = window.setInterval(() => go(current.value + 1), props.autoplay)
  }
}
watch(() => props.autoplay, resetTimer, { immediate: true })

/* 触摸事件 */
const onTouchStart = (e: TouchEvent) => {
  if (timer) window.clearInterval(timer)
  startX = e.touches[0].pageX
  startY = e.touches[0].pageY
  locked = false
}
const onTouchMove = (e: TouchEvent) => {
  if (locked) return
  deltaX = e.touches[0].pageX - startX
  const deltaY = e.touches[0].pageY - startY
  // 角度锁:主要横向才处理
  if (Math.abs(deltaY) > Math.abs(deltaX)) {
    locked = true
    return
  }
  e.preventDefault() // 需要 passive:false,主动声明
}
const onTouchEnd = () => {
  if (locked) return
  if (deltaX > props.threshold) go(current.value - 1)
  else if (deltaX < -props.threshold) go(current.value + 1)
  deltaX = 0
  resetTimer()
}

onMounted(() => {
  const el = container.value!
  el.addEventListener('touchstart', onTouchStart, { passive: true })
  el.addEventListener('touchmove', onTouchMove, { passive: false })
  el.addEventListener('touchend', onTouchEnd, { passive: true })
})
onBeforeUnmount(() => {
  const el = container.value!
  el.removeEventListener('touchstart', onTouchStart as any)
  el.removeEventListener('touchmove', onTouchMove as any)
  el.removeEventListener('touchend', onTouchEnd as any)
  if (timer) window.clearInterval(timer)
})
</script>

<template>
  <div class="swipeable" ref="container">
    <div
      class="track"
      :style="{
        transform: `translate3d(${-current * 100}%, 0, 0)`,
        transition: `transform ${duration}ms ease-out`
      }"
    >
      <div
        v-for="(item, i) in list"
        :key="i"
        class="slide"
        :aria-hidden="i !== current"
      >
        <slot :item="item" :index="i" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.swipeable { overflow: hidden; touch-action: pan-y; }
.track { display: flex; will-change: transform; }
.slide { width: 100%; flex-shrink: 0; }
</style>

使用示例

<Swipeable v-model:index="page" :list="imgs" :loop="true" :autoplay="4000">
  <template #default="{ item }">
    <img :src="item" style="width:100%;display:block;">
  </template>
</Swipeable>

亮点

  1. 组合式 API 拆分逻辑,方便 tree-shaking;
  2. v-model:index 语法糖,父组件无需监听 @change;
  3. 被动事件 + RAF 节流,低端安卓不卡顿;
  4. 事件清理 + onBeforeUnmount,防止 HMR 内存泄漏;
  5. SSR 安全:所有 window 调用都包在 onMounted;
  6. 插槽渲染,业务零耦合;
  7. 无障碍 aria-hidden 同步当前索引。

拓展思考

  1. 双端一致性:桌面端鼠标拖拽如何实现?
    思路:把 mousemove 转成 touchmove 同一套 delta 计算,加 mouseleave 兜底。
  2. 纵向滑动冲突:嵌在长列表里,如何只让横向滑动?
    方案:在 touchmove 里动态开关 touch-action: pan-y,满足角度锁后锁定纵向。
  3. 性能极限:100 张高清图如何不炸内存?
    虚拟滚动 + IntersectionObserver 懒加载,仅保留当前及前后各 1 张真实节点,其余用占位色块。
  4. 微前端输出:
    import { defineCustomElement } from 'vue'
    export const SwipeableCE = defineCustomElement(Swipeable)
    // 在 React 老项目里直接 <swipeable-ce>
    
  5. 单元测试:
    jsdom 无触摸事件,可注入 Touch 构造器模拟;用 Vitest 的 vi.useFakeTimers 测 autoplay 触发次数。
  6. 设计令牌:把 threshold、duration 抽成 CSS 变量,方便 UI 走查一键调参。