1. 使用DOM+Vue的原理性实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/vue@3.2.37/dist/vue.runtime.global.prod.js"></script>
</head>
<body>
<h2>正在获取<span style="color: red;">0</span>号用户的信息</h2>
<button>获取用户数据</button>
<ul>
</ul>
<script>
const { ref, watchEffect } = Vue;
const id = ref(0)
//将userInfo的内容加入到列表中
function renderUser(userInfo,color) {
let ul = document.querySelector("ul")
let li = document.createElement("li");
li.innerHTML = userInfo;
li.style.color=color
ul.appendChild(li)
}
watchEffect((onCleanup) => {
document.querySelector("h2>span").innerHTML = id.value
let controller = new AbortController()
fetch("http://localhost:7002?id=" + id.value, { signal: controller.signal })
.then(resp => resp.text())
.then(userInfo => renderUser(userInfo))
.catch(e => {
//如果请求被取消,则处将会有DOMException抛出,说明用户已经将请求abort掉了
//此时可以将被abort掉的用户id放入到列表中
renderUser((id.value - 1) + "已经取消!",'green')
})
//将“取消请求的函数”放置到待执行队列中,新的请求来临时,队列中的函数将会被执行
//本次的abort,将会导致上一次的请求产生异常,在catch中进行处理
onCleanup(() => controller.abort())
})
let btn = document.querySelector("button")
btn.addEventListener("click", () =>++id.value)
</script>
</body>
</html>
2. 使用响应式+VDom的完整实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/vue@3.2.37/dist/vue.global.prod.js"></script>
</head>
<body>
<div id="app">
<h2>正在获取第<span :style="{color:'red'}">{{id}}</span>号的信息</h2>
<button @click="()=>++id">获取用户信息</button>
<ul>
<li v-for="u of users">{{u}}</li>
</ul>
</div>
<script>
const {ref,watchEffect,createApp} =Vue;
createApp({
setup(){
const id=ref(0)
const users=ref([])
watchEffect((onCleanup)=>{
let controller=new AbortController()
fetch("http://localhost:7002?id="+id.value,{signal:controller.signal})
.then(resp=>resp.text())
.then(user=>users.value.push(user))
.catch(e=>{
//如果请求被取消,则处将会有DOMException抛出,说明用户已经将请求abort掉了
users.value.push((id.value-1)+" 已经被取消。")
})
//将“取消请求的函数”放置到待执行队列中,新的请求来临时,队列中的函数将会被执行
onCleanup(()=>controller.abort())
})
return {id,users}
}
})
.mount("#app")
</script>
</body>
</html>
3. 结合axios,异步方法,自定义指令的版本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/vue@3.2.37/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/axios@0.27.2/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<h2>正在获取第<span :style="{color:'red'}">{{id}}</span>号的信息</h2>
<button @click="change">获取 {{id}} 号用户信息{{wattingInfo}}</button>
<ul>
<li v-tip="'green'" v-for="u of users">{{u}}</li>
</ul>
</div>
<script>
const {ref,watchEffect,createApp} =Vue;
createApp({
directives:{//根据列表中的文字,进行变色的自定义指令(v-tip=green)
tip:(el,binding)=>{
if(el.textContent.includes('取消')){
el.style.color=binding.value
}
}
},
setup(){
const id=ref(0)
const wattingInfo=ref("......")//按钮中的等待提示
const users=ref([])
//改变id的按钮事件处理
function change(){
id.value++;
wattingInfo.value="......"
}
watchEffect(async (onCleanup)=>{
let controller=new AbortController()
//将“取消请求的函数”放置到待执行队列中,新的请求来临时,队列中的函数将会被执行
onCleanup(()=>controller.abort())
try{
let user= await axios({url:"http://localhost:7002?id="+id.value,method:"GET",signal:controller.signal})
.then(resp=>resp.data)
users.value.push(user)
wattingInfo.value=""
}catch(e){
users.value.push((id.value-1)+" 已经被取消。")
}
})
return {id,users,wattingInfo,change}
}
})
.mount("#app")
</script>
</body>
</html>
4.附录: 慢速服务的egg.js实现:
'use strict';
const Controller = require('egg').Controller;
function fn(){
return new Promise((resolv,reject)=>{
setTimeout(()=>{
resolv("johnyu"+Math.random())
},2000)
})
}
class HomeController extends Controller {
async index() {
const { ctx } = this;
let id=ctx.request.query.id
//一个延迟3秒的异步访问
const info=await fn()
ctx.body = "用户:"+id +"的详细信息";
}
}
module.exports = HomeController;