请求路径
const HOST = "http://123.57.142.211:8080";
function request(options, cb) {
var xhr = new XMLHttpRequest();
var url = HOST + options.path;
if (options.query) {
url += "?" + options.query;
}
xhr.open(options.method, url);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var data = JSON.parse(xhr.responseText);
cb(data);
}
}
}
懒加载函数
function throttle(cb,wait){
var timer;
return function(){
if(timer) return;
timer = setTimeout(function(){
cb();
timer = null;
},wait)
}
}
案例
window.onscroll = throttle(function () {
var windowHeight = document.documentElement.clientHeight;
var scrollHeight = document.documentElement.scrollTop;
var htmlHeight = document.documentElement.scrollHeight;
if (windowHeight + scrollHeight >= htmlHeight - 5) {
console.log("1")
}
}, 2000);
<template>
<div class="quanbufenlei">
//这里的懒加载是针对下面这个lodding的操作
<template v-if="flag2"> //flag2控制lodding的显示隐藏
<van-loading size="24px" vertical>加载中...</van-loading>
</template>
</div>
</template>
<script>
export default {
name: "quanbufenlei",
data() {
return {
list:[],
count: 1,
flag2: false,
flag3: true,
};
},
created() {
this.sendlist();
window.onscroll = this.throttle(() => {
var windowHeight = document.documentElement.clientHeight;
var scrollHeight = document.documentElement.scrollTop;
var htmlHeight = document.documentElement.scrollHeight;
if (windowHeight + scrollHeight >= htmlHeight - 10) {
if (this.flag3) {
this.flag3 = false;
this.count += 1;
this.flag2 = true;
this.$http.get("/api/RoomApi/game").then((data) => {
this.flag2 = false;
this.flag3 = true;
this.list = data.data.data.splice(0, this.count * 30);
console.log(this.list);
});
}
}
}, 0);
},
methods: {
throttle(cb, wait) {
var timer;
return function () {
if (timer) return;
timer = setTimeout(function () {
cb();
timer = null;
}, wait);
};
},
sendlist() {
this.$http.get("/api/RoomApi/game").then((data) => {
this.flag2 = true;
this.list = data.data.data.splice(0, 30); 将得到的数据截取30份
console.log(this.list);
});
},
},
};
</script>
<style scoped lang="scss">
.van-loading { .//lodding样式
width: 100px;
height: 100px;
margin: 300px auto;
}
</style>
点击元素让其跳转并携带数据
比如div我想点击让他跳转,并且带走我这个请求获得的数据,那么可以给div加个onclick=“xj(this)”,及时for循环有很多个也不用遍历,此时this就是我们点击的元素,例如:
for(let i=0;i<data.length;i++){
<div data-id=`${data[i].id}` data-name=`${data[i].name}` onclick="xj(this)"></div>
}
function xj(a){
console.log("1")
console.log(a.data.id,a.data.name)
location.href=`./index.html?id=${a.data.id}&name=${a.data.name}`,即可
url编码和解码操作
const url = window.location.href; // 可以获取浏览器完整地址:http://localhost:5173/
var cs_arr1 = url.split("?")[1]; //获取?之后的参数字符串
var cs_arr2 = cs_arr1.split("&"); //参数字符串分割为数组
var cs = {};
for (var i = 0; i < cs_arr2.length; i++) {
//遍历数组,拿到json对象
cs[cs_arr2[i].split("=")[0]] = cs_arr2[i].split("=")[1];
}
console.log(cs); //{"annualid": "2526","user_id": "67677","sex": "%22%E7%94%B7%22","age": "20"}
回车键发送请求
window.addEventListener("keyup", function (e) {
if (e.key == "Enter") {
btn[0].click();
}
})