用Vue在移动端作滚动加载,使用mint-ui框架, InfiniteScroll指令loadmore组件,在uc浏览器和qq浏览器都没法触发。无奈我只能本身写了。
javascript
决定用vue 的自定义指令 写滚动加载。html
核心的apivue
let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
let bodyHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
思路给window绑定滚动事件,用 if(滚动条高度 + 浏览器窗口高度 >= 内容高度 - 阈值) 做为判断条件。咱们把自定义指令命名为 scrolljava
directives: { /** * 滚动加载的自定义指令 */ scroll: { bind: function (el, binding, vnode) { window.addEventListener('scroll', vnode.context.scrollLoad) },
//路由转跳到其余页面时,会调用unbind,解绑滚动加载事件。 unbind: function (el,binding, vnode) { window.removeEventListener('scroll', vnode.context.scrollLoad) } } }, methods: { scrollLoad() { //滚动条高度(页面被卷去高度) let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; //文档高度 let bodyHeight = document.body.scrollHeight || document.documentElement.scrollHeight; if (scrollTop + window.innerHeight >= bodyHeight - 50) { //判断请求发送标志位,避免重复请求(这个须要本身在data里声明,直接贴代码会报错。默认为false,发送请求前改成true, 请求完成回调函数里改回false) if (this.loading) return; //发送请求 this.getnewsData(); }, getnewsData() {/*发送请求的函数*/} },
有一个重点,由于发送请求和滚动事件的方法定义在了组件的methods中,须要拿到Vue实例,但在自定义指令里,不能经过this拿到Vue实例,而是经过指令钩子函数的第三个参数vnode的context属性拿node
必需要在unbind钩子中解绑滚动加载事件,不然在其余页面也会被触发。api
使用 时,由于基于文档高度和滚动条高度,绑在哪里无所谓,这里绑定到容器上就能够了。浏览器
<template> <section v-scroll> <ul> <template v-for="data in datas"> <li> .......... </li> </template> </ul> </section> </template>
以上内容,转载请注明出处 https://www.cnblogs.com/lijinwen/p/8444400.html框架