文件路径 src-directive-loadMore.js
export default {
mounted(el, binding) {
const fn = binding.value
function handleScroll() {
const scrollHeight = el.scrollHeight
const offsetHeight = el.offsetHeight
const scrollTop = el.scrollTop
if (scrollHeight - offsetHeight - scrollTop === 0) {
console.log(scrollHeight, offsetHeight, scrollTop)
fn()
}
}
// 监听滚动事件,调用 handleScroll
el.addEventListener('scroll', handleScroll)
}
}
Ï
文件路径 src-directive-index.js
const modules = import.meta.glob('../directive/**/*.js', {
eager: true
})
let mapDirective = new Map()
Object.keys(modules).forEach((key) => {
if (modules[key] && modules[key].default) {
const newKey = key.replace(/^\.\/|\.ts|\.js/g, '')
mapDirective.set(newKey, modules[key].default)
}
})
// console.log(mapDirective);
export default (app) => {
mapDirective.forEach((value, key) => {
app.directive(key, value)
})
}
main.js入口文件引入directive并注册
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.use(directive)
使用
<template>
<div v-loadMore="scrollBottom">
<ul>
<li v-for="item in list">{{ item }}</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue'
const list ref([])
const scrollBottom = () => {
// ajax请求处理
}
<script>