这篇文章给大家介绍怎么在Vue中实现无限滚动加载指令,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
一、获取滚动条位置
class Scroll {
static get top() {
return Math.max(document.documentElement.scrollTop || document.body.scrollTop);
}
static get clientHeight() {
return Math.max(document.documentElement.clientHeight || document.body.clientHeight);
}
static get clientWidth() {
return Math.max(document.documentElement.clientWidth || document.body.clientWidth);
}
static get height() {
return Math.max(document.documentElement.scrollHeight || document.body.scrollHeight);
}
static get width() {
return Math.max(document.documentElement.scrollWidth || document.body.scrollWidth);
}
static get bottom() {
return Scroll.height - Scroll.clientHeight - Scroll.top;
}
}
二、给根节点绑定滚动事件
vue给body元素绑定滚动条事件,真TMD草蛋。事件绑定上去了 妈的 就是不触发事件。不知道什么鬼问题。
最后直接给根节点HTML绑定滚动事件。
const on = (function () {
if (document.addEventListener) {
return function (element, event, handler) {
if (element && event && handler) {
element.addEventListener(event, handler, false);
}
};
} else {
return function (element, event, handler) {
if (element && event && handler) {
element.attachEvent('on' + event, handler);
}
};
}
})();
三、注册全局指令
/**
* 降低事件执行频率
*/
const downsampler = (function () {
let result = null;
return function (time, func) {
if (!result) {
result = setTimeout(function () {
func();
result = null;
}, time);
}
}
})();
Vue.directive("infinite-scroll", {
bind(el, binding, vnode) {
on(window, 'scroll', function () {
if (typeof binding.value === "function" && Scroll.bottom <= 50) { // 小于50就触发
downsampler(50, binding.value); // 降低触发频率
}
})
}
});
四、实例:
<div class="app" v-infinite-scroll="coupon">
<template v-for="item in goods">
<p>{{item}}</p>
</template>
</div>
let v = new Vue({
el: ".app",
data(){
return {
goods:[]
}
},
methods: {
coupon() {
this.goods.push("你呵呵")
}
}
})
Vue是一套用于构建用户界面的渐进式JavaScript框架,Vue与其它大型框架的区别是,使用Vue可以自底向上逐层应用,其核心库只关注视图层,方便与第三方库和项目整合,且使用Vue可以采用单文件组件和Vue生态系统支持的库开发复杂的单页应用。
关于怎么在Vue中实现无限滚动加载指令就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。