本篇内容主要讲解“Vue中路由怎么切换终止异步请求”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue中路由怎么切换终止异步请求”吧!
问题:
在SPA
模式开发当中,比如VUE
,当前路由切换的时候如何终止正在发生的异步请求呢。
结果:
假如请求超时并且有设定超时时间。有一堆的异步请求在执行,当用户切换到另一个页面,这些请求还未终止,并且当服务器响应之后,反馈的结果不是当前页面所期待的。最终会误导用户造成一些不必要的结果。也给web
造成性能问题。
解决方案:
把执行的请求存入队列,当路由切换的时候终止队列里的异步请求。
首先搞一棵树来存储请求队列
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
let store = new Vuex.Store({
state: {
requests: [],
},
});
new Vue({
el: "#app",
router: router,
render: (h) => h(App),
store,
});
利用ajax
请求和终止
var xhr = $.ajax({
type: "POST",
url: "xxxsx",
data: "",
success: function () {
alert("ok");
},
});
//xhr.abort() 终止请求
this.$store.state.requests.push(xhr);
利用superagent
请求和终止
const request = require('superagent')
var xhr = request('post','/api/xxxx/xxxx')
xhr.send(data)
//xhr.query(data) //get 传参
xhr.end((err,res)=>{
...todo...
})
//xhr.abort() 终止请求
this.$store.state.requests.push(xhr)
利用axios
请求
import axios from "axios";
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios
.get("/api/xxxxx/xxxxx", {
cancelToken: source.token,
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log("Request canceled", thrown.message);
} else {
// 处理错误
}
});
// 取消请求(message 参数是可选的)
//source.cancel('Operation canceled by the user.');
this.$store.state.requests.push(source);
利用vue-resource
请求
import Vue from "vue";
import req from "vue-resource";
Vue.use(req);
this.$http
.get("/someUrl", {
before(request) {
this.$store.state.requests.push(request);
//request.abort(); 终止请求
},
})
.then(
(response) => {
// success callback
},
(response) => {
// error callback
}
);
利用fetch
请求
fetch貌似无法监控读取进度和终端请求,他没有 timeout 机制,没有 progress 提示,但是可以利用 Promise 来实现终止
var _fetch = (function (fetch) {
return function (url, options) {
var abort = null;
var abort_promise = new Promise((resolve, reject) => {
abort = () => {
reject("abort.");
console.info("abort done.");
};
});
var promise = Promise.race([fetch(url, options), abort_promise]);
promise.abort = abort;
return promise;
};
})(fetch);
var xhr = _fetch("/api/xxx/xxxx", { methods: "POST", body: data });
xhr.then(
function (res) {
console.log("response:", res);
},
function (e) {
console.log("error:", e);
}
);
xhr.abort(); //终止
this.$store.state.requests.push(xhr);
那么知道如何终止请求,然后也存储了请求实例,剩下的只要监听路由就行了
let router = new Router({....})
//每次路由改变之前终止所有的请求实例
router.beforeEach(function (to, from, next) {
this.$store.state.requests.forEach(xhr=>xhr.abort()) //终止所有的请求实例
this.$store.state.requests =[] //执行完清空,等待下一次的页面的请求装载
next()
})
这种只是假设,自然请求完成之后最好,还是手动释放树的请求示例。例如ajax请求完成之后在complite里面splice store里面的实例。
到此,相信大家对“Vue中路由怎么切换终止异步请求”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。