创建完项目后,安装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>