一、在src目录下新建一个directive文件夹,在里面新建一个index.ts
// 全局自定义指令
const GlobalDirective = (app: any) => {
// 表格滚动上拉加载
app.directive('loadmore', {
mounted(el: any, binding: any, vnode: any, prevVNode: any) {
const scrollVNode = el.querySelector('.el-scrollbar__wrap')
// 表格滚动
let currentScroll = 0,
lastScroll = 0,
isDownScroll = true
scrollVNode.addEventListener(
'scroll',
function (event: any) {
// 判断是否向上滚动
// debugger
currentScroll = event.target.scrollTop
if (lastScroll < currentScroll) {
isDownScroll = true
} else {
isDownScroll = false
}
lastScroll = currentScroll
// 定一个距离,距离底部当前距离时候触发加载事件
const sign = 10
// 判断是否到底
const scrollDistance = event.target.scrollHeight - event.target.scrollTop - event.target.clientHeight
if (scrollDistance <= sign && isDownScroll) {
binding.value.eventH()
}
},
false
)
}
});
}
export default GlobalDirective
二、main.ts中全局引用
// 引入全局指令
import GlobalDirective from '@/plugins/directive/directive'
const app = createApp(App);
GlobalDirective(app)
三、.vue文件中使用
<el-table
v-loadmore="{ eventH: () => loadMore() }"
:data="state.tableData"
:height="
state.tableData.length * 54 >= state.height
? state.height + 'px'
: (state.tableData.length * 54 < 270 ? 270 : state.tableData.length * 54) + 'px'
"
style="width: 100%; border-radius: 4px; overflow: auto"
>
const state = reactive({
height: null,
isFinished: false, // 是否所有已加载完
tableData: [],
total: 0
})
const pageParams: any = ref({
page: 1,
rows: 5 //一页5条数据
});
// 获取数据
const getDataList = async (isLoadmore: boolean = false) => {
const res = await getList({
...params.value,
...pageParams.value
});
// debugger
if(isLoadmore){
// debugger
state.tableData=state.tableData.concat(res?.rows || [])
}else{
state.tableData=res.rows || []
// debugger
}
state.total=res.total;
// 是否所有数据已加载完
state.isFinished = state.total <= state.tableData.length
};
// 加载
let num = 0 // 需要定义一个变量来存储请求次数,防止重复请求
const loadMore = async () => {
// 防止重复加载
num++
if (num <= 1 && !state.isFinished) {
pageParams.value.page++;
await getDataList(true)
num = 0
}
}