Vue3.0虚拟滚动条|vue3自定义美化滚动条V3Scroll

Vue3-Scroll 基于vue3.0构建的桌面端虚拟美化滚动条组件。

一款基于vue3.x构建的pc端自定义模拟滚动条|vue3.0美化滚动条组件。支持监听DOM尺寸变化、是否原生滚动、是否自动隐藏滚动条、自定义尺寸/颜色及层级等功能。

引入组件

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'

// 引入滚动条组件v3scroll
import V3Scroll from './components/v3scroll'

createApp(App).use(V3Scroll).mount('#app')

快速使用

<!-- //自定义参数 -->
<v3-scroll size="10" color="#ff5588" zIndex="1000">
    <p>显示自定义内容!</p>
</v3-scroll>

<!-- //scroll事件处理 -->
<v3-scroll @scroll="handleScroll">
    <p>显示自定义内容!</p>
</v3-scroll>

效果和饿了么滚动条组件有些类似。并且支持监听DOM尺寸改变,动态更新滚动条

参数配置

v3scroll支持如下参数自定义配置。

props: {
    // 是否显示原生滚动条
    native: Boolean,
    // 是否自动隐藏滚动条
    autohide: Boolean,
    // 滚动条尺寸
    size: { type: [Number, String], default: '' },
    // 滚动条颜色
    color: String,
    // 滚动条层级
    zIndex: null
},

组件模板

<template>
    <div class="vui__scrollbar" ref="ref__box" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave" v-resize="handleResize">
        <div :class="['vscroll__wrap', {native: native}]" ref="ref__wrap" @scroll="handleScroll">
            <div class="vscroll__view" v-resize="handleResize">
                <slot />
            </div>
        </div>
        <div :class="['vscroll__bar vertical']" @mousedown="handleClickTrack($event, 0)" :style="{'width': parseInt(size)>=0 ? parseInt(size)+'px' : '', 'z-index': parseInt(zIndex)>=0 ? parseInt(zIndex) : ''}">
            <div class="vscroll__thumb" ref="ref__barY" :style="{'background': color, 'height': barHeight+'px'}" @mousedown="handleDragThumb($event, 0)"></div>
        </div>
        <div :class="['vscroll__bar horizontal']" @mousedown="handleClickTrack($event, 1)" :style="{'height': parseInt(size)>=0 ? parseInt(size)+'px' : '', 'z-index': parseInt(zIndex)>=0 ? parseInt(zIndex) : ''}">
            <div class="vscroll__thumb" ref="ref__barX" :style="{'background': color, 'width': barWidth+'px'}" @mousedown="handleDragThumb($event, 1)"></div>
        </div>
    </div>
</template>

自定义指令directive

vue2.x和vue3中使用自定义指令有些不一样。

// vue 2
const MyDirective = {
    bind(el, binding, vnode, prevVnode) {},
    inserted() {},
    update() {},
    componentUpdated() {},
    unbind() {}
}

// vue 3
const MyDirective = {
    beforeMount(el, binding, vnode, prevVnode) {},
    mounted() {},
    beforeUpdate() {},
    updated() {},
    beforeUnmount() {},
    unmounted() {}
}

v3scroll核心逻辑处理。

/**
 * @Desc     Vue3.0虚拟滚动条组件V3Scroll
 * @Time     andy by 2021-01
 * @About    Q:282310962  wx:xy190310
 */
<script>
    import { onMounted, ref, reactive, toRefs, nextTick } from 'vue'
    import domUtils from './utils/dom'
    export default {
        props: {
            // ...
        },
        
        /**
         * Vue3.x自定义指令写法
         */
        // 监听DOM尺寸变化
        directives: {
            'resize': {
                beforeMount: function(el, binding) {
                    let width = '', height = '';
                    function get() {
                        const elStyle = el.currentStyle ? el.currentStyle : document.defaultView.getComputedStyle(el, null);
                        if (width !== elStyle.width || height !== elStyle.height) {
                            binding.value({width, height});
                        }
                        width = elStyle.width;
                        height = elStyle.height;
                    }
                    el.__vueReize__ = setInterval(get, 16);
                },
                unmounted: function(el) {
                    clearInterval(el.__vueReize__);
                }
            }
        },
        setup(props, context) {
            const ref__box = ref(null)
            const ref__wrap = ref(null)
            const ref__barX = ref(null)
            const ref__barY = ref(null)

            const data = reactive({
                barWidth: 0,            // 滚动条宽度
                barHeight: 0,           // 滚动条高度
                ratioX: 1,              // 滚动条水平偏移率
                ratioY: 1,              // 滚动条垂直偏移率
                isTaped: false,         // 鼠标光标是否按住滚动条
                isHover: false,         // 鼠标光标是否悬停在滚动区
                isShow: !props.autohide, // 是否显示滚动条
            })

            onMounted(() => {
                nextTick(() => {
                    updated()
                })
            })

            // 鼠标滑入
            const handleMouseEnter = () => {
                data.isHover = true
                data.isShow = true
                updated()
            }

            // 鼠标滑出
            const handleMouseLeave = () => {
                data.isHover = false
                data.isShow = false
            }

            // 拖动滚动条
            const handleDragThumb = (e, index) => {
                const elWrap = ref__wrap.value
                const elBarX = ref__barX.value
                const elBarY = ref__barY.value

                data.isTaped = true
                let c = {}
                // 阻止默认事件
                domUtils.isIE() ? (e.returnValue = false, e.cancelBubble = true) : (e.stopPropagation(), e.preventDefault())
                document.onselectstart = () => false

                if(index == 0) {
                    c.dragY = true
                    c.clientY = e.clientY
                }else {
                    c.dragX = true
                    c.clientX = e.clientX
                }

                // ...
            }

            // 点击滚动槽
            const handleClickTrack = (e, index) => {
                // ...
            }

            // 更新滚动区
            const updated = () => {
                if(props.native) return
                const elBox = ref__box.value
                const elWrap = ref__wrap.value
                const elBarX = ref__barX.value
                const elBarY = ref__barY.value

                let barSize = domUtils.getScrollBarSize()

                // 垂直滚动条
                if(elWrap.scrollHeight > elWrap.offsetHeight) {
                    data.barHeight = elBox.offsetHeight **2 / elWrap.scrollHeight
                    data.ratioY = (elWrap.scrollHeight - elBox.offsetHeight) / (elBox.offsetHeight - data.barHeight)
                    elBarY.style.transform = `translateY(${elWrap.scrollTop / data.ratioY}px)`
                    // 隐藏系统滚动条
                    if(barSize) {
                        elWrap.style.marginRight = -barSize + 'px'
                    }
                }else {
                    data.barHeight = 0
                    elBarY.style.transform = ''
                    elWrap.style.marginRight = ''
                }

                // 水平滚动条
                // ...
            }

            // 滚动区元素/DOM尺寸改变
            const handleResize = () => {
                // 执行更新操作
            }

            // ...

            return {
                ...toRefs(data),
                ref__box, ref__wrap, ref__barX, ref__barY,

                handleMouseEnter, handleMouseLeave,
                handleDragThumb, handleClickTrack,
                updated,
                
                // ...
            }
        }
    }
</script>

<v3-scroll @scroll="handleScroll">
	<p><img src="https://cn.vuejs.org/images/logo.png" style="height:250px;" /></p>
	<p>内容信息!这里是内容信息!这里是内容信息!这里是内容信息!这里是内容信息!</p>
</v3-scroll>

setup(){
	// 监听滚动事件
	handleScroll(e) {
		this.scrollTop = e.target.scrollTop
		// 判断滚动状态
		if(e.target.scrollTop == 0) {
			this.scrollStatus = '到达顶部'
		} else if(e.target.scrollTop + e.target.offsetHeight >= e.target.scrollHeight) {
			this.scrollStatus = '到达底部'
		}else {
			this.scrollStatus = '滚动中....'
		}
	}
	
	// ...
}

Okay,基于vue3.x开发自定义滚动条组件就分享到这里。希望对大家有些帮助!💪🏻

vue3.0网页端弹窗组件V3Layer

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaoyan_2018

你的鼓励将是我持续作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值