企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] #### Vue 中 Axios 防止多次请求 1. main.js 入口文件全局绑定axios ~~~ import Vue from 'vue' import './plugins/axios' import App from './App.vue' import router from './router' import Axios from 'axios'; Vue.prototype.$http = Axios Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app') ~~~ ***** 2. 组件中使用 >[danger] 注意:需要先定义cancelRequest() 方法,然后再axios 请求前 先调用该方法 cancelRequest() 此方法用于终止请求 ~~~ methods: { // 1. 定义终止请求方法 cancelRequest() { if (typeof this.source === 'function') { this.source('终止请求!') } }, getData() { // 2. 先调用终止请求方法 this.cancelRequest() // 3. 注意 this 指向 let that = this; // 4. 请求服务器api this.$http.get(`/api/searchList?cityId=10&kw=${this.keywords}`, { cancelToken: new this.$http.CancelToken( function executor(c) { that.source = c } ) }) .then(res => { if (res.data.msg === 'ok') { this.list = res.data.data.movies.list } }).catch(err => { if (err) { if (this.$http.isCancel(err)) { // 终止多次请求 请求取消 返回取消后的信息 console.log('请求取消', err.message) } else { // 服务端数据异常 console.log('没有搜索到数据哦') this.list = [] } } }) } } ~~~