封装代码
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
注意事项
- 外层的div需要设置为 position: relative;
网友评论