vue3系列:vue3.0自定義虛擬滾動條V3Scroll|vue3模擬滾動條組件

基於Vue3.0構建PC桌面端自定義美化滾動條組件V3Scroll。css

前段時間有分享一個Vue3 PC網頁端彈窗組件,今天帶來最新開發的Vue3.0版虛擬滾動條組件。html

V3Scroll 使用vue3.x開發的輕量級自定義美化滾動條組件。功能效果基本和以前的vue2版保持一致。支持是否自動隱藏滾動條、自定義滾動條尺寸、顏色及層級等功能。vue

功能效果相似餓了麼el-scrollbar組件。而且支持監聽DOM尺寸改變,動態更新滾動條。node

◆ 快速引入

main.js中全局引入滾動條v3scroll組件。react

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>...</v3-scroll>  包裹內容塊,便可快速實現一個精緻的替代原生滾動條組件。app

<!-- //自定義參數 -->
<v3-scroll size="12" color="#a96950" zIndex="2021">
    <p>這裏顯示自定義內容!</p>
</v3-scroll>

<!-- //scroll事件處理 -->
<v3-scroll @scroll="handleScroll">
    <p>這裏顯示自定義內容!</p>
</v3-scroll>

◆ 編碼實現

v3scroll支持以下參數自定義配置。dom

props: {
    // 是否顯示原生滾動條
    native: Boolean,
    // 是否自動隱藏滾動條
    autohide: Boolean,
    // 滾動條尺寸
    size: { type: [Number, String], default: '' },
    // 滾動條顏色
    color: String,
    // 滾動條層級
    zIndex: null
},

v3scroll組件模板ide

<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>

注意:vue3.0中自定義指令directive和vue2中有些不同。ui

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

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

下面介紹下在vue3.0中使用自定義指令。編碼

// Vue3中自定義指令 - 監聽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__);
        }
    }
}
/**
 * @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 ref="scrollRef">
    <p>這裏是內容信息!這裏是內容信息!</p>
</v3-scroll>

<p>
    <span class="vs__btn" @click="handleScrollTo('top')">滾動至頂部</span>
    <span class="vs__btn" @click="handleScrollTo('bottom')">滾動至底部</span>
    <span class="vs__btn" @click="handleScrollTo(150)">滾動至150px</span>
</p>

setup() {
    // 滾動到指定位置
    const handleScrollTo = (val) => {
        scrollRef.value.scrollTo(val)
    }
}

OK,基於Vue3開發自定義模擬滾動條組件就分享到這裏。但願你們能喜歡哈~😃

最後附上一個Vue3.0移動端彈框組件

vue3.0手機端彈層組件:http://www.javashuo.com/article/p-wafhykwt-ny.html

相關文章
相關標籤/搜索