【问题标题】:TypeScript/Nuxt.js/Vuex: Access methods from imported classTypeScript/Nuxt.js/Vuex:导入类的访问方法
【发布时间】:2021-02-26 19:16:27
【问题描述】:

我正在使用 typescript 构建一个 nuxt.js 应用程序,并希望将 API 调用与 vuex 存储区分开来。但似乎我在导入类时无法使用这些方法。当我试图调用一个方法时,编译器也只会说TS1005: ',' expected.

apiClient.ts

export default class apiClient {
    helloWorld() {
        console.log('Hello World');
    }
}

products.ts:

import ApiClient from '../services/apiClient';

export const actions = {
  ApiClient.helloWorld();
};

tsconfig.json

 "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./src/*"
      ],
      "@/*": [
        "./src/*"
      ]
    },
    "types": [
      "@types/node",
      "@nuxt/types",
      "@nuxtjs/axios"
    ]
  },

【问题讨论】:

    标签: typescript nuxt.js vuex


    【解决方案1】:

    您的代码存在多个问题。

    第一个问题是你不能这样定义你的动作。您将函数直接写入操作对象,这不是对象的工作方式。您需要定义一个键并将您的功能分配给它,如下所示:

    export const actions = {
      helloWorld: ApiClient.helloWorld,
    };
    

    请注意缺少的括号,因为您正在分配函数而不是执行它。

    但是该代码仍然无法编译,因为您在类中定义了方法。这样做没有错,但如果你这样做,你将不得不使用 new 关键字来实例化你的类(或者你可以让你的类静态,如果你知道怎么做的话):

    import ApiClient from '../services/apiClient';
    const client = new ApiClient();
    
    export const actions = {
      helloWorld: client.helloWorld,
    };
    

    在你的情况下,我一开始就不会使用类。您可以直接导出您的函数,这更容易:

    export const helloWorld = () => {
      console.log('Hello World');
    };
    

    现在导入也更容易了。您也可以省略该密钥,如果您保持它与导出它的名称相同:

    import { helloWorld } from '../services/apiClient';
    
    export const actions = {
      helloWorld,
      // or use a different name:
      hello: helloWorld,
    };
    

    我希望这可以解决您的问题,并且您明白为什么它不起作用。

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 2013-01-07
      • 2020-07-16
      • 2019-03-05
      • 2019-12-04
      • 2020-09-10
      • 2021-07-17
      • 1970-01-01
      • 2018-11-18
      相关资源
      最近更新 更多