您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)使用Vue怎么實現(xiàn)一個滾動到頁面底部無限加載數(shù)據(jù)功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
創(chuàng)建項目
首先創(chuàng)建一個簡單的vue項目
# vue init webpack-simple infinite-scroll-vuejs
然后安裝項目所需要用的一些插件
# npm install axios moment
初始化用戶數(shù)據(jù)
項目搭建完后, 跑起來看看
# npm run dev
打開http://localhost:8080無誤后, 我們開始修改代碼, 先看看獲取用戶數(shù)據(jù)這塊,
<script> import axios from 'axios' import moment from 'moment' export default { name: 'app', // 創(chuàng)建一個存放用戶數(shù)據(jù)的數(shù)組 data() { return { persons: [] } }, methods: { // axios請求接口獲取數(shù)據(jù) 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() { // 在頁面掛載前就發(fā)起請求 this.getInitialUsers() } } </script>
這里原作者也專門提醒, 完全沒有必要也不建議在加載頁面的時候請求5次, 只是這個接口一次只能返回1條數(shù)據(jù), 僅用于測試才這樣做的. 當(dāng)然我這里也可以通過Mock來模擬數(shù)據(jù), 就不詳細(xì)說了~
接下來來寫模板結(jié)構(gòu)和樣式, 如下:
<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()來監(jiān)聽滾動, 并且這個事件是應(yīng)該在mounted()這個生命周期內(nèi)的. 代碼如下:
<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>
關(guān)于使用Vue怎么實現(xiàn)一個滾動到頁面底部無限加載數(shù)據(jù)功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。