vue中axios防止多次触发终止多次请求的示例代码(
网络编程 2021-07-04 15:02www.168986.cn编程入门
这篇文章主要介绍了vue中axios防止多次触发终止多次请求的实现方法(防抖),本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
需求
例如在搜索框中,并不是你输入一个字就需要渲染一次数据,而是取最后一次的输入内容进行搜索。
连续按下 AAAAA ,只取最后一次按下时搜索框的内容(即:AAAAA)进行搜索。 而不是搜索跟 A(第一次按下),AA(第二次按下),AAA相关联的内容
本文例子: 检测用户输入的值,监测这个值,然后根据值调用接口查询结果
代码:
<template> <input type="text" v-model="message"> <template> <script> import axios from "axios"; export default { data(){ return{ message:'' }, watch : { message(newVal){ var that = this; // 取消上一次请求 this.cancelRequest(); axios.get('/api/searchList?cityId=10&kw='+ newVal, { cancelToken: new axios.CancelToken(function(c) { that.source = c; }) }).then((res) => { // 在这里处理得到的数据 //数据逻辑处理 }).catch((err) => { if (axios.isCancel(err)) { console.log('Rquest canceled', err.message); //请求如果被取消,这里是返回取消的message } else { //handle error console.log(err); } }) } }, methods: { cancelRequest(){ if(typeof this.source ==='function'){ this.source('终止请求') } } } } </script>
其他做法:
可以使用 clearTimeout() setTimeout() 截取,设置一定时常请求一次
总结
以上所述是长沙网络推广给大家介绍的vue中axios防止多次触发终止多次请求的实现方法(防抖),希望对大家有所帮助!
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程