vue.js 实现下拉无限滚动加载新数据

效果,到页面底部后下拉获取新数据,无限滚动

Random User API 一次只会返回一个随机用户数据,

 

您需要创建一个名为scroll()的新函数,并将其加载到mounted()生命周期方法中。

这个scroll()方法应该有一个简单的条件来计算页面的底部,判断它为true或false,并执行一些操作。我们将利用文档对象的documentElement.scrollTopdocumentElement.offsetHeight属性和窗口的innerHeight属性来确定是否滚动到底部

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

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      persons: []
    };
  },
  methods: {
    getInitialUsers() {
      for (var i = 0; i < 5; i++) {
        this.$ajax.get(`https://randomuser.me/api/`).then(response => {
          console.log(response);
          this.persons.push(response.data.results[0]);
        });
      }
    },
    scroll(person) {
      window.onscroll = () => {
        let bottomwindow =
          document.documentElement.scrollTop + window.innerHeight ===
          document.documentElement.offsetHeight; //scrollTop滚动条的垂直位置,innerheight	返回窗口的文档显示区的高度。
        console.log(bottomwindow);
        console.log(document.documentElement.offsetHeight); //返回该元素的像素高度,高度包含该元素的垂直内边距和边框,且是一个整数

        if (bottomwindow) {
          //如果滚动最底部就变为true
          this.$ajax.get(`https://randomuser.me/api/`).then(response => {
            console.log(response);
            this.persons.push(response.data.results[0]);
          });
        }
      };
    }
  },
  beforeMount() {
    this.getInitialUsers();
  },
  mounted() {
    this.scroll(this.person);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped 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>

 

使用scss 请使用npm 安装 ,看我博客的其它文章安装scss 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值