Typescript中使用Axios
1)Vue.prototype
在vue項目main.js文件中:
Vue.prototype.$appName = 'My App'這樣你可以通過在原型上定義它們使其在每個 Vue 的實例中可用。
2)Axios create的含義
// 2.學會使用axios.create( )創建axios實例
// var instance = axios.create({
// baseURL: 'https://some-domain.com/api/',
// timeout: 1000,
// headers: {'X-Custom-Header': 'foobar'}
// });
// 創建實例的好處:統一(批量)處理request/response
// (1)例如你在每次的請求中都要帶 cookie, 你或許可以在每個請求中這么寫:
?
// axios.get('/user1',{withCredentials:true});
// axios.get('/user2',{withCredentials:true});
// ... ...
// 但是你也可以這么用:
?
// var instance = axios.create({
// withCredentials:true
// });
// instance.get('/user1').then();
// instance.get('/user2').then();
// ... ...
// (2)如果你的多個請求前綴都是相同的,那么你就可以使用baseUrl
// bad:
?
// axios.get('http://www.baidu.com/api/city').then();
// axios.get('http://www.baidu.com/api/region').then();
// axios.get('http://www.baidu.com/api/user').then();
// good:
?
// var instance = axios.create({
// baseUrl: http://www.baidu.com/api
// });
// instance.get('/city').then();
// instance.get('/region').then();
// instance.get('/user').then();
3)Vue聲明的補充類型
// 插件可以增加 Vue 的全局/實例屬性和組件選項。在這些情況下,在 TypeScript 中制作插件需要類型聲明。慶幸的是,TypeScript 有一個特性來補充現有的類型,叫做模塊補充 (module augmentation)。
?
// 例如,聲明一個 string 類型的實例屬性 $myProperty:
?
// // 1. 確保在聲明補充的類型之前導入 'vue'
// import Vue from 'vue'
?
// // 2. 定制一個文件,設置你想要補充的類型
// // 在 types/vue.d.ts 里 Vue 有構造函數類型
// declare module 'vue/types/vue' {
// // 3. 聲明為 Vue 補充的東西
// interface Vue {
// $myProperty: string
// }
// }
4)定義如下?
import Vue from "vue";
import { AxiosInstance } from "axios";
declare module "vue/types/vue" {
interface Vue {
$http: AxiosInstance;
}
}
?
5)main.ts中的代碼
const http = axios.create({
baseURL : 'http://localhost:3000'
})
?
Vue.prototype.$http = http
Vue.prototype.$httpajax = http
?
總結
以上是生活随笔為你收集整理的Typescript中使用Axios的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: axios入门实践
- 下一篇: 为什么使用 Vuetify?