text: import { ref, watch, nextTick, computed } from 'vue'
  
  export default function useFixed (props) {
    const TITLE_HEIGHT = 30
    const groupRef = ref(null)
    const listHeights = ref([])
    const scrollY = ref(0)
    const currentIndex = ref(0)
    const distance = ref(0)
  
    // 填充fixedTitle内容
    const fixedTitle = computed(() => {
      if (scrollY.value < 0) {
        return ''
      }
      const currentGroup = props.data[currentIndex.value]
      return currentGroup ? currentGroup.title : ''
    })
  
    // 计算标题小于距离的时候，添加滑动样式
    const fixedStyle = computed(() => {
      const distanceVal = distance.value
      const diff = (distanceVal > 0 && distanceVal < TITLE_HEIGHT) ? distanceVal - TITLE_HEIGHT : 0
      return {
        transform: `translate3d(0, ${diff}px, 0)`
      }
    })
  
    // 监听获取每个组的区间高度
    watch(() => props.data, async () => {
      await nextTick()
      calculate()
    })
  
    // 监听newY落在哪个区间内，获取当前展区标题的索引
    watch(scrollY, (newY) => {
      const listHeightsVal = listHeights.value
      for (let i = 0; i < listHeightsVal.length - 1; i++) {
        const heightTop = listHeightsVal[i]
        const heightBottom = listHeightsVal[i + 1]
        if (newY >= heightTop && newY <= heightBottom) {
          currentIndex.value = i
          distance.value = heightBottom - newY
        }
      }
    })
  
    // 获取每个组的区间高度
    function calculate () {
      const list = groupRef.value.children
      const listHeightsVal = listHeights.value
      let height = 0
  
      listHeightsVal.length = 0
      listHeightsVal.push(height)
  
      for (let i = 0; i < list.length; i++) {
        height += list[i].clientHeight
        listHeightsVal.push(height)
      }
    }
  
    // 监听滚动事件，拿到实时滚到的位置
    function onScroll (pos) {
      scrollY.value = -pos.y
    }
  
    return {
      groupRef,
      onScroll,
      fixedTitle,
      fixedStyle,
      currentIndex
    }
  }
  