繁体   English   中英

如何在 Vue (Typescript) 中使用 axios?

[英]How to use axios in Vue (Typescript)?

我想在 vue (Typescript) 中使用 axios,但我的代码遇到了麻烦。 这是我的 main.ts

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

这是我的 Vue 代码截图

这是我第一次使用typescript,之前我在javascript中使用了另一种方式,我没有任何问题,那么我如何在TypeScript中使用它呢?

感谢您的时间和解决方案。

我这样做并在 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;
  }
}

我将 HTTP/REST 操作封装在单独的.ts文件中。 在这里,我还使用 async/await 来获得更好的可读性代码。 每个方法都声明了它的输入和返回类型。

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
}

您确定使用 POST 请求吗? 由于“GetTreeTenant”,这似乎是 GET 请求,您只能尝试 axios 而不是 $axios。

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

在打字稿中,我们可以使用模块扩充。 https://v2.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 {
}}

我想建议您使用 axios 为您的 http 请求使用服务。 我会通过将我的 http 服务分成单独的文件来做到这一点。 假设您有一个 API,并且您使用了一个资源,比如说hero ,那么代码将如下所示:

// services/http.ts

import axios from 'axios';

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

对于英雄服务,您可以这样做:

// 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();

一种快速而肮脏的解决方案是将您的 Vue 对象设置为 type any。 TypeScript 让您知道它无法识别 Vue 对象上的 $axios 属性。

当你告诉 TypeScript Vue 对象可以是任何东西时,你可以添加任何你想要的属性。

const app : any = new Vue({})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM