美文网首页
基于perfect-scrollbar的vue自定义滚动指令

基于perfect-scrollbar的vue自定义滚动指令

作者: 风凌摆渡人 | 来源:发表于2023-06-09 17:45 被阅读0次

    封装代码

    import PerfectScrollbar from 'perfect-scrollbar'
    import 'perfect-scrollbar/css/perfect-scrollbar.css'
    import { ObjectDirective } from 'vue'
    const usePerfectScrollbar = () => {
      let ps: null | PerfectScrollbar
      const resize = () => {
        ps && ps.update()
      }
      return {
        install(el: Element | string) {
          if (el) {
            ps = new PerfectScrollbar(el, {
              wheelSpeed: 2,
              wheelPropagation: true,
              scrollingThreshold: 100,
              minScrollbarLength: 10
            })
            window.addEventListener('resize', resize, false)
            return ps
          }
        },
        uninstall() {
          window.removeEventListener('resize', resize, false)
          ps && ps.destroy()
        }
      }
    }
    
    const { install, uninstall } = usePerfectScrollbar()
    
    const scrollbar: ObjectDirective = {
      mounted(el: HTMLElement) {
        install(el)
      },
      unmounted() {
        uninstall()
      }
    }
    
    
    export default scrollbar
    

    引入

    npm i perfect-scrollbar
    或
    pnpm i perfect-scrollbar
    或
    yarn add perfect-scrollbar
    
    
    const app = createApp(App)
    app.directive('scrollbar', Scrollbar)
    

    调用

    <div class="content" v-scrollbar>
      <div class="item" v-for="(itm, inx) in list" :key="inx" :style="{ background: itm.color }"></div>
    </div>
    

    效果

    1686390029735-c8963761-6a4e-4c87-aaf8-92f8af94b3d4.png

    注意事项

    1. 外层的div需要设置为 position: relative;

    相关文章

      网友评论

          本文标题:基于perfect-scrollbar的vue自定义滚动指令

          本文链接:https://www.haomeiwen.com/subject/yzuzedtx.html