需求
最近在做移动端电影项目的搜索组件的时候,发现每次输入都会调接口访问,要实现的是“不是每次输入都调用接口,而是取最后一次输入的值”
有两种方法实现,
- 在watch中首先使用clearTimeout(),然后在后面开启一个新的定时器setTimeout(),将axios请求写到后面可以实现但是不推荐使用
- axios自带的
下面直接看代码
<template>
<input type="text" v-model="message">
</template>
<script>
export default {
data() {
return {
message:'',
searchMovieList:[]
};
},
watch:{
message(val){
var vm = this
// 取消上一次请求
vm.cancelRequest();
//如果val是2021,输入2进行一次请求,输入0取消对2的请求,输入2取消对0的请求,输入1取消对2的请求,最终以val=1请求数据
vm.$http.get(`/ajax/search?cityId=10&stype=-1&kw=`+val, {
cancelToken: new vm.$http.CancelToken(function(c) {
vm.source = c;
})
}).then(res => {
//这里是成功的请求后渲染数据
}).catch((err) => {
if (vm.$http.isCancel(err)) {
console.log('Rquest canceled', err.message); //请求如果被取消,这里是返回取消的message
} else {
console.log(err);
}
})
}
},
methods: {
cancelRequest(){
if(typeof this.source ==='function'){
this.source('终止请求')
}
}
},
}
</script>
最后给大家看效果图