vue中mock创建数据(带分页),post获取数据后,实现滚动加载更多数据

本文介绍了如何在Vue项目中使用MockJS模拟POST请求的数据,创建了一个获取列表的Mock接口,并通过Axios进行数据交互。在main.js中全局引入Axios,并在test.vue组件中实现页面滚动时动态加载数据的功能,同时展示了如何监听滚动事件并应用防抖函数防止频繁请求。
摘要由CSDN通过智能技术生成

创建完项目后,安装mock

npm install mockjs

先在src目录下创建mock.js

在mock.js中输入:

// 引入mockjs
const Mock = require('mockjs')
//post 请求
Mock.mock('/mock/getList','post',function(option){
  // console.log(JSON.parse(option.body));//可以打印option看下,需要先在vue页面中引用参能看到
  //option为post传递的数据 
  //page 为页码    pageNum为每页显示多少条数据
  var page=JSON.parse(option.body).page, pageNum=JSON.parse(option.body).pageNum
  var list=[]
  for (let i = 0; i < 200; i++) {
    var newlist={
      id:i,
      title:Mock.mock('@ctitle'),   //@ctitle 在mock中同Random.title()  随机创建一个表题
      content:Mock.mock('@csentence') //@csentence 同Random.csentence() 随机创建一句话
    }
    //根据页码和数量 返回的数据
    if(i<page*pageNum&&i>=(page-1)*pageNum){
        list.push(newlist)
    }
  }
  return list
})

数据随便创建:查看更多mock创建数据方法

安装axios

npm i axiso

在main.js中输入:

import Vue from 'vue'
import App from './App.vue'
import router from './router' 
import axios from 'axios'
require("./mock")

//
Vue.prototype.$axios=axios


new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')

创建test.vue页面,并设置好路由
在test.vue中输入:

<template>
  <div class="page" ref="scrollView">
    <button @click="getData">获取数据</button>
    <ul>
      <li v-for="item in dataList" :key="item.id">
        title:{{ item.title }} content:{{ item.content }}
      </li>
    </ul>
    <p class="loadding" v-if="isShowLoad">{{ showLoadText }}</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      dataList: [],
      page: 1,
      pageNum: 50,
      isShowLoad: false,
      showLoadText: "加载中...",
    };
  },
  mounted() {
   document.addEventListener("scroll", this.preventShake(this.scrollFn, 500))
  },
  methods: {
    getData() {
      this.isShowLoad = true;
      this.$axios
        .post("/mock/getList", {
          page: this.page,
          pageNum: this.pageNum,
        })
        .then((res) => {
          if (res.data.length != 0) {
            this.dataList = [...this.dataList, ...res.data];
            this.isShowLoad = false;
          } else {
            this.showLoadText = "暂无更多数据";
            setTimeout(() => {
              this.isShowLoad = false;
            }, 2000);
          }
        });
      this.page++;
    },
    scrollFn(){
   		 // scrollHeight:document的滚动高度
        let scrollHeight= document.documentElement.scrollHeight || document.body.scrollHeight;
         //nowScotop :可视区高度 
        let nowScotop = document.documentElement.clientHeight || document.body.clientHeight; 
         //wheight:已滚动高度
        let wheight= document.documentElement.scrollTop || document.body.scrollTop;
        if(wheight>scrollHeight-nowScotop-5){
          this.getData()
        }
    },
    //防抖 (一定要加,不然会一直请求接口)
    preventShake(fn, time) {    
        var timeout = null;    
        return function() {        
            if(timeout !== null)   clearTimeout(timeout);        
            timeout = setTimeout(fn, time);    
        }
    }

  },
};
</script>

<style scoped>
.page {
  position: relative;
}
.loadding {
  width: 100px;
  height: 50px;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  background-color: rgba(0, 0, 0, 0.3);
  color: #fff;
  text-align: center;
  line-height: 50px;
}
</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值