实现一个简单的vue无限加载指令方法

2020-06-16 06:18:28易采站长站整理

node.innerHTML = oldContent+content;
}

这样就实现了无限加载。

在 vue 中使用指令实现

为什么要用指令实现呢?好像只有指令是可以获取到底层 dom 的?而实现无限加载,是需要拿到内容高度的。

首先初始化一个项目,添加一个组件,用来显示列表。


// components/Index.vue
<template>
<div>
<ul class="news">
<li class="news__item" v-for="(news, index) in newslist">
{{index}}-{{news.title}}
</li>
</ul>
</div>
</template>
<style>
.news__item {
height: 80px;
border: 1px solid #ccc;
margin-bottom: 20px;
}
</style>
<script>
export default{
data(){
return{
newslist: [
{title: 'hello world'},
{title: 'hello world'},
{title: 'hello world'},
{title: 'hello world'},
{title: 'hello world'},
{title: 'hello world'},
{title: 'hello world'},
{title: 'hello world'},
{title: 'hello world'},
{title: 'hello world'}
] }
}
}
</script>

OK,现在开始编写指令。从传统实现中,我们了解到要注册对滚动事件对监听,同时拿到内容高度。


directives: {
scroll: {
bind: function (el, binding){
window.addEventListener('scroll', ()=> {
if(document.body.scrollTop + window.innerHeight >= el.clientHeight) {
console.log('load data');
}
})
}
}
}

首先是在组件内注册了 scroll 指令,然后在指令第一次绑定到组件时,也就是对应着 bind钩子,注册滚动监听。

钩子函数就是一些生命周期改变时会调用的函数。bind 在第一次绑定到组件时调用、unbind 在指令与组件解绑时调用。

还可以注意到 bind 对应到函数有两个参数,el 和 binding,这是钩子函数参数,比如 el 对应绑定的节点,binding 有很多数据,比如传给指令的参数等。

下面的el.clientHeight就是表示获取绑定指令的这个节点的内容高度。

和之前一样,判断滚动的高度加上窗口高度是否大于内容高度。

绑定指令到节点上:


<template>
<div v-scroll="loadMore">
<ul class="news">
<li class="news__item" v-for="(news, index) in newslist">
{{index}}-{{news.title}}
</li>
</ul>
</div>
</template>

可以看到给指令传了一个值,这个值就是加载数据的函数:


methods: {
loadMore() {
let newAry = [];