前端封装一个移动端(已支持PC)滚动的组件

安装

npm install @better-scroll/core --save

引入

import BScroll from '@better-scroll/core'

直接上代码

Scroll.vue

<template>
  <div ref="rootRef">
    <slot></slot>
  </div>
</template>

<script>
import useScroll from './use-scroll'
import {
    
     ref } from 'vue'

export default {
    
    
  // eslint-disable-next-line
  name: 'scroll',
  props: {
    
    
    click: {
    
    
      type: Boolean,
      default: true
    },
    probeType: {
    
    
      type: Number,
      default: 0
    }
  },
  emits: ['scroll'],
  setup (props, {
     
      emit }) {
    
    
    const rootRef = ref(null)
    const scroll = useScroll(rootRef, props, emit)

    return {
    
    
      rootRef,
      scroll
    }
  }
}
</script>

use-scroll.js

import BScroll from '@better-scroll/core'
import ObserveDOM from '@better-scroll/observe-dom'
import {
    
     onMounted, onUnmounted, onActivated, onDeactivated, ref } from 'vue'

BScroll.use(ObserveDOM)

export default function useScroll (wrapperRef, options, emit) {
    
    
  const scroll = ref(null)

  onMounted(() => {
    
    
    const scrollVal = scroll.value = new BScroll(wrapperRef.value, {
    
    
      observeDOM: true, // 监听数据的变化,dom自动更新, 执行refresh, 内部重新计算
      ...options
    })

    if (options.probeType > 0) {
    
    
      scrollVal.on('scroll', (pos) => {
    
    
        emit('scroll', pos)
      })
    }
  })

  onUnmounted(() => {
    
    
    scroll.value.destroy()
  })

  onActivated(() => {
    
    

  })
  onDeactivated(() => {
    
    

  })
  return scroll
}

使用

在这里插入图片描述

高阶Scroll组件的实现

import {
    
     h, mergeProps, withCtx, renderSlot, ref, computed, watch, nextTick } from 'vue'
import Scroll from '@/base/Scroll/Scroll.vue'
import {
    
     useStore } from 'vuex'

export default {
    
    
  name: 'wrap-scroll',
  props: Scroll.props,
  emits: Scroll.emits,
  render (ctx) {
    
     // ctx上下文 可以理解为this
    return h(Scroll, mergeProps({
    
    
      ref: 'scrollRef'
    }, ctx.$props, {
    
    
      onScroll: (e) => {
    
    
        ctx.$emit('scroll', e)
      }
    }), {
    
    
      default: withCtx(() => {
    
    
        return [renderSlot(ctx.$slots, 'default')]
      })
    })
  },
  setup() {
    
    
    const scrollRef = ref(null)
    const scroll = computed(() => {
    
    
      return scrollRef.value.scroll
    })

    const store = useStore()
    const playlist = computed(() => store.state.playlist)

    watch(playlist, async () => {
    
    
      await nextTick()
      scroll.value.refresh()
    })

    return {
    
    
      scrollRef,
      scroll
    }
  }
}

import Scroll from '@/components/wrap-scroll'

完事

猜你喜欢

转载自blog.csdn.net/weixin_44582045/article/details/131168658