vue3基于perfect-scrollbar实现自定义滚动条

2,175 阅读1分钟

perfect-scrollbar 一个全浏览器适用的自定义scrollbar,本文主要演示vue3通过hooks与directive实现方法

www.npmjs.com/package/per…

安装

yarn add perfect-scrollbar

创建usePerfectScrollbar.ts

import PerfectScrollbar from 'perfect-scrollbar'
import 'perfect-scrollbar/css/perfect-scrollbar.css'

export default function usePerfectScrollbar() {
    let ps: null | PerfectScrollbar
    const resize = () => {
        ps && ps.update()
    }
    return {
        install(el: Element | string) {
            if(el){
                ps = new PerfectScrollbar(el, {
                    wheelSpeed: 2,
                    wheelPropagation: false
                })
                window.addEventListener('resize', resize, false)
                return ps
            }
        },
        uninstall() {
            window.removeEventListener('resize', resize, false)
            ps && ps.destroy()
        }
    }
}

创建scrollbarDirective.ts

import { App } from 'vue'
import usePerfectScrollbar from '@/hooks/usePerfectScrollbar'

export default {
    install(app: App) {
        const { install, uninstall } = usePerfectScrollbar()
        app.directive('scrollbar', {
            mounted(el) {
                install(el)
            },
            beforeUnmount() {
                uninstall()
            }
        })
    }
}

在main.ts中注册指令

import scrollbarDirective from '@/directive/scrollbarDirective'
const app = createApp(App)
app.use(scrollbarDirective)

使用

<div v-scrollbar></div>

使用中遇到的问题

官方的css中ps类没有带相对定位,需要给.ps加上position:relative