maioyan
maioyan copied to clipboard
如何使用axios自带的防抖~
如何使用axios自带的防抖~
export default {
name: "searchPage",
data() {
return {
query: "",
movieList: [], // 存放电影列表数据
cancelTokenFn: null
};
},
// 使用watch发起监听异步请求
watch: {
query: function(newVal) {
// console.log(newVal);
// 发送axios请求
// 设置函数抖动
const _this = this;
const CancelToken = this.axios.CancelToken;
this.cancelTokenFn && this.cancelTokenFn();
this.cancelTokenFn = null;
// 在axios函数中,加一个参数。
this.axios
.get("/api/searchList?cityId=10&kw=" + newVal, {
cancelToken: new CancelToken(function executor(c) {
_this.cancelTokenFn = c;
})
})
.then(res => {
// console.log(res)
// console.log(res.data.data.movies);
if (newVal && res.status === 200 && res.data.data.movies.list) {
this.movieList = res.data.data.movies.list;
}
})
.catch(err => {
console.log(err);
});
if (newVal === "") {
this.movieList.length = 0;
}
}
}
};