首页 > 语言 > JavaScript > 正文

Vue下滚动到页面底部无限加载数据的示例代码

2024-05-06 15:19:48
字体:
来源:转载
供稿:网友

看到一篇Implementing an Infinite Scroll with Vue.js , 觉得挺实用的就看了下, 顺便简单翻译了一下给需要的人参考.

从这个项目中可以加深对Vue的生命周期的理解, 何时开始axios请求, 如何结合Vue使用原生js来写scroll事件等等, 我这里主要是对原文的重点提取和补充

本文技术要点

    Vue生命周期 axios简单用法 moment.js格式化日期 图片懒加载 结合原生js来写scroll事件 请求节流

创建项目

首先创建一个简单的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">  <h1>Random User</h1>  <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>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选