SHARE
TWEET

Untitled

a guest Oct 15th, 2019 93 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * 关于 axios cancel token 的配置
  3.  * 当 Vue 单页应用,一个页面请求未完全结束就被调走到其他路由的时候
  4.  * 需要把前一个页面的未完成的请求,全部干掉,不影响当前路由的请求
  5.  */
  6. import Vue from 'vue'
  7. import App from './App.vue'
  8. import router from './router'
  9.  
  10. // Axios configuration
  11. window.axios = require('axios')
  12. // ... other config
  13.  
  14. // Axios request interceptors
  15. // 定义 cancel token
  16. let requestSource = { token: null, cancel: null }
  17. const CancelToken = window.axios.CancelToken
  18.  
  19. // 打断 axios 请求,当 config.cancelToken 有值的时候,请求会被 cancel 掉
  20. window.axios.interceptors.request.use(config => {
  21.   config.cancelToken = requestSource.token
  22.   return config
  23. }, error => {
  24.   return Promise.reject(error)
  25. })
  26.  
  27. // Router Before Each Configuration
  28. // 在进入每个新路由之前,给 axios 的 cancel token 赋值
  29. router.beforeEach((to, from, next) => {
  30.   requestSource.cancel && requestSource.cancel()
  31.   requestSource = CancelToken.source()
  32.   next()
  33. })
  34.  
  35. new Vue({
  36.   router,
  37.   render: h => h(App)
  38. }).$mount('#app')
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top