使用Vue自定義指令實現列表下拉加載

使用Vue自定義指令實現列表下拉加載

參考鏈接: https://www.cnblogs.com/Neilisme/p/10245588.html

1、在 main.js 同級創建 directive.js 註冊自定義指令

import Vue from 'vue'

Vue.directive('more', {
    bind(el, binding) {
        var p = 0;
        var t = 0;
        var down = true;
        el.addEventListener('scroll', function() {
            //判斷是否向下滾動
            p = this.scrollTop;
            if(t < p){
                down = true;
            }else{
                down = false;
            }
            t = p;
            const scrollDistance = this.scrollHeight - this.scrollTop - this.clientHeight;
            if (scrollDistance <= 0 && down) {
                // 滾動到底部後觸發事件
                binding.value()
            }
        });
    }
})

2、在main.js中引入 使用 directives

import * as directives from './directives'

Vue.use(directives)

3、在需要添加下拉加載更多的元素上 加 樣式和自定義指令

  • v-more 後加下拉後需要觸發的事件loadMore

  • 樣式中明確該元素的固定高度,設置scroll

<div v-more="loadMore" style="height:230px;overflow:scroll;">
    <CheckboxGroup v-model="onePatient" @on-change="checkOneItem">
        <Checkbox v-for="(item, index) in patientList" :key="index" v-model="item.checked" :label="item.patientName">
            {{item.patientName}}
            {{item.patientSexText}}
            {{item.age === '-' ? '' : `${item.age}歲`}}
        </Checkbox>
    </CheckboxGroup>
</div>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章