vue切換菜單取消未完成接口請求的案例
在做別的功能時 console里面總會報別的菜單接口里的錯 看的很心煩 于是想優化一下 就有了這篇文章 在切換菜單的時候取消所有未完成接口的請求
1.找到自己的請求攔截器 重點是 config.cancelToken = global.store.source.token;
http.interceptors.request.use(config => { config.cancelToken = global.store.source.token; return config}, err => { return Promise.reject(err)})
2.找到自己全局文件夾我的是global.js
global.store = { source: { token: null, cancel: null }}
3.路由
router.beforeEach((to, from, next) => { // ...此處其他代碼省略 // 切換路由時清空上個路由未完成的所有請求 const CancelToken = axios.CancelToken global.store.source.cancel && global.store.source.cancel() global.store.source = CancelToken.source() next()})
補充知識:父組件如何獲取子組件數據,子組件如何獲取父組件數據,父子組件如何傳值
1、父組件如何主動獲取子組件的數據
方案1:$children
$children用來訪問子組件實例,要知道一個組件的子組件可能是不唯一的,所以它的返回值是個數組
定義Header、HelloWorld兩個組件
<template> <div class='index'> <Header></Header> <HelloWorld :message='message'></HelloWorld> <button @click='goPro'>跳轉</button> </div></template>mounted(){ console.log(this.$children)}
打印的是個數組,可以用foreach分別得到所需要的數據
缺點:
無法確定子組件的順序,也不是響應式的
方案2: $refs
<HelloWorld ref='hello' :message='message'></HelloWorld>
調用hellworld子組件的時候直接定義一個ref,這樣就可以通過this.$refs獲取所需要的數據。
this.$refs.hello.屬性
this.$refs.hello.方法
2.子組件如何主動獲取父組件中的數據
通過$parent
parent用來訪問父組件實例,通常父組件都是唯一確定的,跟children類似
this.$parent.屬性
this.$parent.方法
父子組件通信除了以上三種,還有props和emit。此外還有inheritAttrs和attrs
3.inheritAttrs
這是2。4新增的屬性和接口。inheritAttrs屬性控制子組件html屬性上是否顯示父組件提供的屬性。
如果我們將父組件Index中的屬性desc、ketsword、message三個數據傳遞到子組件HelloWorld中的話,如下
父組件Index部分
<HelloWorld ref='hello' :desc='desc' :keysword='keysword' :message='message'></HelloWorld>
子組件:HelloWorld,props中只接受了message
props:{ message: String }
實際情況,我們只需要message,那其他兩個屬性則會被當作普通的html元素插在子組件的根元素上
這樣做會使組件預期功能變得模糊不清,這個時候,在子組件中寫入,inheritAttrs:false,這些沒用到的屬性便會被去掉,true的話,就會顯示。
props:{ message: String },inheritAttrs:false
如果父組件沒被需要的屬性,跟子組件本來的屬性沖突的時候
<HelloWorld ref='hello' type='text' :message='message'></HelloWorld>
子組件:helloworld
<template> <input type='number'></template>
這個時候父組件中type='text',而子組件中type='number',而實際中最后顯示的是type='text',這并不是我們想要的,所以只要設置inheritAttrs:false,type便會成為number。
那么上述這些沒被用到的屬性,如何被獲取。這就用到了$attrs
3.$attrs
作用:可以獲取到沒有使用的注冊屬性,如果需要,我們在這也可以往下繼續傳遞。
就上述沒有用到的desc和keysword就能通過$attrs獲取到
通過$attr的這個特性可以父組件傳遞到子組件,免除父組件傳遞到子組件,再從子組件傳遞到孫組建的麻煩
父組件Index部分
<div class='index'> <HelloWorld ref='hello' :desc='desc' :keysword='keysword' :message='message'></HelloWorld></div>
子組件helloworld部分
<div class='hello'> <sunzi v-bind='$attrs'></sunzi> <button @click='aa'>獲取父組件的數據</button></div>
孫組建
<template> <div class='header'> {{$attrs}} <br> </div></template>
可以看出通過v-bind='$attrs'將數組傳到孫組建中
除了以上,provide/inject也適用于隔代組件通信,尤其是獲取祖先組建的數據,非常方便
provide 選項應該是一個對象或返回一個對象的函數
provide:{ for:’demo’ }inject:[’for’]
以上這篇vue切換菜單取消未完成接口請求的案例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: