温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Vue怎么实现一个滚动到页面底部无限加载数据功能

发布时间:2021-04-08 17:25:55 来源:亿速云 阅读:439 作者:Leah 栏目:web开发

这篇文章将为大家详细讲解有关使用Vue怎么实现一个滚动到页面底部无限加载数据功能,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

创建项目

首先创建一个简单的vue项目

# vue init webpack-simple infinite-scroll-vuejs

然后安装项目所需要用的一些插件

# npm install axios moment

初始化用户数据

项目搭建完后, 跑起来看看

# npm run dev

打开http://localhost:8080无误后, 我们开始修改代码, 先看看获取用户数据这块,

<script>
import axios from 'axios'
import moment from 'moment'
export default {
 name: 'app',
 // 创建一个存放用户数据的数组
 data() {
  return {
   persons: []
  }
 },
 methods: {
  // axios请求接口获取数据
  getInitialUsers() {
   for (var i = 0; i < 5; i++) {
    axios.get(`https://randomuser.me/api/`).then(response => {
     this.persons.push(response.data.results[0])
    })
   }
  },
  formatDate(date) {
   if (date) {
    return moment(String(date)).format('MM/DD/YYYY')
   }
  },
 beforeMount() {
  // 在页面挂载前就发起请求
  this.getInitialUsers()
 }
}
</script>

这里原作者也专门提醒, 完全没有必要也不建议在加载页面的时候请求5次, 只是这个接口一次只能返回1条数据, 仅用于测试才这样做的. 当然我这里也可以通过Mock来模拟数据, 就不详细说了~

接下来来写模板结构和样式, 如下:

<template>
 <div id="app">
  <h2>Random User</h2>
  <div class="person" v-for="(person, index) in persons" :key="index">
   <div class="left">
    <img :src="person.picture.large" alt="">
   </div>
   <div class="right">
    <p>{{ person.name.first}} {{ person.name.last }}</p>
    <ul>
     <li>
      <strong>Birthday:</strong> {{ formatDate(person.dob)}}
     </li>
     <div class="text-capitalize">
      <strong>Location:</strong> {{ person.location.city}}, {{ person.location.state }}
     </div>
    </ul>
   </div>
  </div>
 </div>
</template>

<style lang="scss">
.person {
 background: #ccc;
 border-radius: 2px;
 width: 20%;
 margin: 0 auto 15px auto;
 padding: 15px;

 img {
  width: 100%;
  height: auto;
  border-radius: 2px;
 }

 p:first-child {
  text-transform: capitalize;
  font-size: 2rem;
  font-weight: 900;
 }

 .text-capitalize {
  text-transform: capitalize;
 }
}
</style>

这样页面就能显示5个人的个人信息了.

处理无限滚动加载逻辑

我们接下来需要在methods里面添加scroll()来监听滚动, 并且这个事件是应该在mounted()这个生命周期内的. 代码如下:

<script>
 // ...
 methods: {
  // ...
  scroll(person) {
   let isLoading = false
   window.onscroll = () => {
    // 距离底部200px时加载一次
    let bottomOfWindow = document.documentElement.offsetHeight - document.documentElement.scrollTop - window.innerHeight <= 200
    if (bottomOfWindow && isLoading == false) {
     isLoading = true
     axios.get(`https://randomuser.me/api/`).then(response => {
      person.push(response.data.results[0])
      isLoading = false
     })
    }
   }
  }
 },
 mounted() {
  this.scroll(this.persons)
 }
}
</script>

关于使用Vue怎么实现一个滚动到页面底部无限加载数据功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI