英文:
Cancel a previous axios request on new request in Vue Js
问题
我试图实现一个搜索功能,使用 @input 每当输入框的文字发生变化时,从后端加载用户数据并填充到datalist中。现在,每次变化都会生成一个新的请求,而旧的请求仍在处理/挂起,这会导致一些问题。我希望在每次新请求发生时取消旧请求。
Vue.js中的HTML代码
<input type="text" class="form-control" placeholder="搜索名称" v-model="forms.name" list="getname" @input="inputData()" required> <datalist id="getInput" > <option v-for="option in options">{{option}}</option> </datalist>
加载数据的函数
axios.get('Url/GetUser/' + this.forms.name).then((response) => {if(response.data.error){ this.errorNya = response.data; this.loading2 = false;}else{ this.errorNya.username = ""; this.options = response.data; this.loading2= false; this.disableButton = true; }
英文:
I am trying to implement a search which loads user data from the backend on every word change using @input and populate in datalist, now for every change a new request is generated while the old request is still processing/pending this causes some problems. I am looking to cancel old request on every new request that will take place.
Html code in vue js
<input type="text" class="form-control" placeholder="Search Name" v-model="forms.name" list="getname" @input="inputData()" required> <datalist id="getInput" > <option v-for="option in options">{{option}}</option> </datalist>
Function to load data
axios.get('Url/GetUser/'+ this.forms.name).then((response) => {if(response.data.error){ this.errorNya = response.data; this.loading2 = false;}else{ this.errorNya.username = ""; this.options = response.data; this.loading2= false; this.disableButton = true; }
答案1
得分: 0
我已查阅文档和其他来源,找到了最适合我的解决方案。
this.cancelFunc();
//下面的代码创建了一个用于取消请求的令牌
let axiosSource = axios.CancelToken.source();
this.request = { cancel: axiosSource.cancel };
//然后我们将令牌传递给我们要取消的请求。
axios.get('/Url/GetUser/' + this.forms.username, { cancelToken: axiosSource.token, }).then((response) => {
if (response.data.error) {
this.errorNya = response.data;
this.loading2 = false;
} else {
this.errorNya.username = "";
this.options = response.data;
this loading2 = false;
this.disableButton = true;
}
},
cancelFunc() {
if (this.request)
this.request.cancel();
},
我知道这可能不是最佳的方法,但这解决了我的问题。
英文:
I have referred the documentation and other sources for this question, and i found a solution which suited me best.
this.cancelFunc();
//Below line creates a cancel token for this request
let axiosSource = axios.CancelToken.source();
this.request = { cancel: axiosSource.cancel };
//then we pass the token to the request we want to cancel.
axios.get('/Url/GetUser/'+ this.forms.username, {cancelToken: axiosSource.token,}).then((response) => {
if (response.data.error) {
this.errorNya = response.data;
this.loading2 = false;
} else {
this.errorNya.username = "";
this.options = response.data;
this.loading2 = false;
this.disableButton = true;
}
},
cancelFunc() {
if (this.request)
this.request.cancel();
},
i know this will not be the best way to do this, but this solved my problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论