Vue 3 Answer
Augmenting Vue to support your custom component properties are done through module augmentation. To add your $http declaration and support it you can create the vue-shim.d.ts file and augment vue/runtime-core
import axios from 'axios'
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$http: typeof axios
}
}
Vue also asserts that for version 3, it's imperative you either import or export as the top level line of code in your ts file to ensure it's treated as a module:
Make sure the declaration file is a TypeScript module In order to take advantage of module augmentation, you will need to ensure there is at least one top-level import or export in your file, even if it is just export {}.
Now when you install your custom plugin, you can hang it off of the app.config.globalProperties object:
// my-custom-plugin.js
import axios from 'axios'
import http from 'plugins/http'
export default {
install (app, options) {
app.config.globalProperties.$http = http
}
}
See below for the answer for Vue 2.
Vue 2 Answer
You can't declare the type of the $http as a value, instead make a new typing:
// http.d.ts
export default interface {
login(credentials: any): PromiseLike<any>
}
Then, in a file like types/vue.d.ts, augment the Vue constructor like:
import http from '@/types/http'
...
interface Vue {
$http: http
}
Now make your http.ts by following the link in the comment above:
import _Vue from 'vue'
import axios from 'axios'
const http = {
login(credentials: any) {
return HTTP.post('/auth', {
account_email: credentials.email,
account_password: credentials.password
})
}
}
export function http(Vue: typeof _Vue): void {
Vue.prototype.$http = http;
}
and now you need to import that http.ts file and Vue.use it in something like main.ts
import Http from '@/http'
Vue.use(Http)
And now your components can consume your http plugin:
mounted() {
this.$http.login(credentials)
.then((response) => console.log(response))
.catch((error) => console.warn(error))
}
$http, it's annoying to import it in every single component.