之前的文章《深入解析js中實現(xiàn)隊列(代碼分享)》中,給大家了解了js中實現(xiàn)隊列。下面本篇文章給大家了解Vue中路由切換終止異步請求,有一定的參考價值,有需要的朋友可以參考一下,希望對你們有所助。
問題:
在SPA
模式開發(fā)當(dāng)中,比如VUE
,當(dāng)前路由切換的時候如何終止正在發(fā)生的異步請求呢。
結(jié)果:
假如請求超時并且有設(shè)定超時時間。有一堆的異步請求在執(zhí)行,當(dāng)用戶切換到另一個頁面,這些請求還未終止,并且當(dāng)服務(wù)器響應(yīng)之后,反饋的結(jié)果不是當(dāng)前頁面所期待的。最終會誤導(dǎo)用戶造成一些不必要的結(jié)果。也給web
造成性能問題。
解決方案:
把執(zhí)行的請求存入隊列,當(dāng)路由切換的時候終止隊列里的異步請求。
首先搞一棵樹來存儲請求隊列
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 參數(shù)是可選的) //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貌似無法監(jiān)控讀取進(jìn)度和終端請求,他沒有 timeout 機(jī)制,沒有 progress 提示,但是可以利用 Promise 來實現(xiàn)終止
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);
那么知道如何終止請求,然后也存儲了請求實例,剩下的只要監(jiān)聽路由就行了
let router = new Router({....}) //每次路由改變之前終止所有的請求實例 router.beforeEach(function (to, from, next) { this.$store.state.requests.forEach(xhr=>xhr.abort()) //終止所有的請求實例 this.$store.state.requests =[] //執(zhí)行完清空,等待下一次的頁面的請求裝載 next() })
這種只是假設(shè),自然請求完成之后最好,還是手動釋放樹的請求示例。例如ajax請求完成之后在complite里面splice store里面的實例。
[完]
推薦學(xué)習(xí):vue.js教程