How to use axios in Vue (Typescript)?

23,420

Solution 1

I do this and work perfectly on main.ts

import Vue from 'vue';
import axios, { AxiosStatic } from 'axios';

axios.defaults.baseURL = 'http://192.168.1.225:8088';
Vue.prototype.$axios = axios;
declare module 'vue/types/vue' {
  interface Vue {
    $axios: AxiosStatic;
  }
}

Solution 2

I'm encapsulate HTTP/REST operations in separate .ts files. Here I also use async/await to have better readable code. Each method declared its input and return types.

import axios from 'axios'

const http = axios.create({
  baseURL: `${SOME_SERVICE_URL}/base-path`,
  headers: { 'Content-Type': 'application/json' }
})

export async function getItemById (itemId: string): Promise<Item> {
  const response = await http.get(`/${itemId}`)
  return response.data
}

export async function createItem (item: Item): Promise<Item> {
  const response = await http.post('/', JSON.stringify(item))
  return response.data
}

Solution 3

Are you sure to use POST request? It seems like GET request because of 'GetTreeTenant' and you can try only axios instead $axios.

let uri = '<url here>';
  this.axios.post(uri, data).then((response) => {
    console.log(response);
});

Solution 4

In typescript,we can use module augmentation. https://vuejs.org/v2/guide/typescript.html#%E5%A2%9E%E5%BC%BA%E7%B1%BB%E5%9E%8B%E4%BB%A5%E9%85%8D%E5%90%88%E6%8F%92%E4%BB%B6%E4%BD%BF%E7%94%A8

declare module 'vue/types/vue' {
interface Vue {
}}

Solution 5

I want to suggest you use a service for your http request using axios. I would do this by separating my http services into separate files. Say you have an API and you use a resource say hero then the code will look something like this:

// services/http.ts

import axios from 'axios';

export default axios.create({
  baseURL: 'http://192.168.1.225:8088',
  params: {
    // API params go here
  }
});

For hero service you could do this:

// services/hero.ts

import http from './http';

export default class HeroService {
  getHero(heroId: string) {
    return axios.get(`heroes/${heroId}`);
  }

  ...
}

// A singleton instance
export const heroService = new HeroService();
Share:
23,420
william
Author by

william

Updated on July 18, 2022

Comments

  • william
    william almost 2 years

    I would like to use axios in vue (Typescript) but I get into trouble with my code. This is my main.ts

    import axios from 'axios'
    Vue.prototype.$axios = axios
    axios.defaults.baseURL = 'http://192.168.1.225:8088'
    

    and this is my vue code screenshot here

    This is the first time I use typescript,before I used it another way in javaScript and I did not have any problem, so how can I use it in TypeScript?

    Thank you for your time and solution.

  • Ярослав Прохоров
    Ярослав Прохоров almost 3 years
    Is there an example of how to call in a component? I also write I can not find $ axios Even after adding this plugin?