看到一篇Implementing an Infinite Scroll with Vue.js , 覺得挺實用的就看了下, 順便簡單翻譯了一下給需要的人參考.
從這個項目中可以加深對Vue的生命周期的理解, 何時開始axios請求, 如何結合Vue使用原生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>這樣頁面就能顯示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上實現其實和普通的頁面開發差不多, 每次滾動加載未完成的情況下不會觸發請求下一次, 每次請求push到數組內, 通過<img :src="">的數據綁定實現了懶加載(其實0 0我不太認可...), 看完是不是感覺挺簡單的.
最后, 我把這個也弄了一份在GitHub上面, 有需要的可以看看infinite-scroll-vuejs-demo~
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答