一、前言

在自定义的搜索框组件内进行搜索数据的时候,通过v-model实时绑定inputMessage,并且在watch里面监听inputMessage的改变并发送请求。

问题也就产生了:

每次输入一个文字,就会发起一个请求,这样不仅会占用网络资源,也会影响用户体验。在连续发送多个请求的过程中,其实前面的输入并没有必要发送出去,只发送最终结果即可,因此需要在发送一次请求的时候直接取消上一次请求

二、代码实现

首先在main.js中引入axios,将axios方法加入Vue的原型中:

//引入axios
import axios from 'axios'
Vue.prototype.$axios = axios

在vue.config.js文件中配置环境设置代理:

需要注意的是,在vue.config.js文件中无法使用es6的exprot default={ ... } 需要使用module.exports={ ... }


module.exports = {
 
    // 项目部署的基本路径
    publicPath: "/",
   
    // 构建输出路径 ,vue-cli-service build 时生成。
    outputDir: "dist",
   
    //放置生成的静态资源 (js、css、img、fonts) 和 outputDir 同级。
    assetsDir: "",
   
    // 是否在开发环境下通过 eslint-loader 在每次保存时 lint 代码
    lintOnSave: true,
   
    //是否使用包含运行时编译器的 Vue 构建版本
    runtimeCompiler: false,
   
    //是否需要 map
    productionSourceMap: true,
   
    // 偏向app
    pwa: {},
   
    devServer: {
      host: 'localhost',
      port: '8080', // 端口号
      https: false, // 是否支持https
      open: false, // 配置自动启动浏览器
      disableHostCheck: true, 
      /* 使用代理 */
      proxy: {
        '/api': {
          /* 目标代理服务器地址 */
          target: "http://localhost:8080/",
          /* 允许跨域 */
          changeOrigin: true,
          pathRewrite: {
            // 调用接口时带 / 使用'' 不带使用 '/',例如 /sys/login 则使用 '' , sys/login 则使用 '/'
            // '^/api': '' 
            '^/api': '/static/mock' 
          }
        }
      },
    }
  }

这里贴出methods和watch里的方法:


methods:{
    cancelRequest(){
      if(typeof this.source ==='function'){
        this.source('终止请求')
      }
    },
  },
  watch:{
    inputMessage(newVal){
      const that = this //get请求中的拦截参数,写成箭头函数的话可以不用that
      //取消上一次的请求
      //如果newVal是1902,输入1进行一次请求,输入9取消对1的请求,输入0取消对9的请求
      this.cancelRequest()  

      this.axios.get('/api/search?userId=' + newVal,{
          cancelToken: new this.axios.CancelToken(function(c) {
            that.source = c;
          })
      }).then((res)=>{
        this.userInfo = res.data.data.userInfo
      }).catch((err) => {
          if (axios.isCancel(err)) {
              console.log('Rquest canceled', err.message); //请求如果被取消,这里是返回取消的message
          } else {
              //handle error
              console.log(err);
          }
      })
    }
  }

大功告成!

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐