在vue项目main.js文件中:
Vue.prototype.$appName = 'My App'
这样你可以通过在原型上定义它们使其在每个 Vue 的实例中可用。
// 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();
// 插件可以增加 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
// }
// }
import Vue from "vue";
import { AxiosInstance } from "axios";
declare module "vue/types/vue" {
interface Vue {
$http: AxiosInstance;
}
}
const http = axios.create({
baseURL : 'http://localhost:3000'
})
Vue.prototype.$http = http
Vue.prototype.$httpajax = http