TypeScript/Nuxt.js/Vuex:从导入的类访问方法



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

apiClient.ts

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

产品.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"
]
},

您的代码存在多个问题。

第一个问题是你不能这样定义你的行为。您正在将函数直接写入actions对象,这不是对象的工作方式。你需要定义一个密钥并将你的功能分配给它,就像这样:

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,
};

我希望这能解决你的问题,你也能理解为什么它不起作用。

最新更新