這篇文章將為大家詳細講解有關使用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怎么實現一個滾動到頁面底部無限加載數據功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。