【问题标题】:Vue CLI + Axios TypeError: XX is not a functionVue CLI + Axios TypeError: XX is not a function
【发布时间】:2021-05-25 12:29:26
【问题描述】:

我是 Vue.js 的新手,我正在尝试通过 Axios 创建一个带有 HTTP 客户端的 Vue CLI。

我找到了this useful setup,因为我正在制作的项目将相当大,我希望它可以作为模板重复使用。我对其进行了一些更新以适应当前版本,但(很可能)不会导致此错误。

我做了一个服务,扩展自提到的 API 类:

import { AxiosRequestConfig, AxiosResponse } from 'axios';
import { apiConfig } from './config/api.config';
import { Api } from './superclasses/api';

const api = '/portals';

export class PortalService extends Api {
  constructor(config: AxiosRequestConfig) {
    super(config);
  }

  public async getPortals(): Promise<AxiosResponse<Portal[]>> {
    return await this.get<Portal, AxiosResponse<Portal[]>>(api);

    // return this.success(portals);
  }
}

export const portalService = new PortalService(apiConfig);

我的问题是,当我在 vue 上下文中使用 portalService 时。它不承认它是一个类。

我有以下 vue 文件,PortalsList.vue:

<template>
  <div class="container">
    <h2>Portals</h2>
    <button @click="getPortals()">Get portals</button>
    <table v-if="portals" class="table table-bordered">
      <thead>
        <tr>
          <th>Portal Id</th>
          <th>Name</th>
          <th>Domain</th>
          <th>File Domain</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in portals" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.domain }}</td>
          <td>{{ item.fileDomain }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { Portal } from '@/interfaces/portal';
import { portalService } from '@/services/portalService';

@Component
export default class PortalsList extends Vue {
  private portals: Portal[] = [];

  public async getPortals() {

    const response = await portalService.getPortals();
    this.portals = response.data;
  }
}
</script>

当我按下“获取门户”按钮时,我在控制台中收到以下错误:

我知道我还有很多东西要学,还有很多信息要查找,但我就是找不到合适的解决方案来解决我的问题,这让我来到了这里。

【问题讨论】:

    标签: typescript rest vue.js npm axios


    【解决方案1】:

    我找到了问题的答案。该方法不是该类的成员,因为它永远不会绑定到 this。 我使用箭头函数以我能找到的最典型的方式解决了这个问题。简单地在构造函数中绑定给了我另一个错误,然后我发现我还必须更正 Api 类中的某些地方。

    生成的portalService.ts 如下所示:

    import { Portal } from '@/interfaces/portal';
    import { AxiosRequestConfig, AxiosResponse } from 'axios';
    import { apiConfig } from './config/api.config';
    import { Api } from './superclasses/api';
    
    const api = '/portals';
    
    export class PortalService extends Api {
      constructor(config: AxiosRequestConfig) {
        super(config);
      }
    
      public getPortals = async (): Promise<Portal[]> => {
        const portals = await this.get<Portal, AxiosResponse<Portal[]>>(api);
        return this.success(portals);
      };
    }
    
    export const portalService = new PortalService(apiConfig);
    
    

    【讨论】: