Javascript 将Axios作为插件添加到Vue/Typescript中
我一直在尝试将Axios添加到Vue原型中,以便可以通过Javascript 将Axios作为插件添加到Vue/Typescript中,javascript,typescript,vue.js,axios,vuetify.js,Javascript,Typescript,Vue.js,Axios,Vuetify.js,我一直在尝试将Axios添加到Vue原型中,以便可以通过this.$http访问它。我使用的是Typescript,所以我也需要它的类型定义。我在互联网上看到很多地方描述了如何做到这一点,但不管我怎么做,Typescript都无法识别我的定义,我得到了错误: 类型上不存在属性“$http” 我认为这与我的tsconfig.json有关,但我不确定。请参阅以下相关文件: src/plugins/axios.ts import _Vue from 'vue'; import Axios from '
this.$http
访问它。我使用的是Typescript,所以我也需要它的类型定义。我在互联网上看到很多地方描述了如何做到这一点,但不管我怎么做,Typescript都无法识别我的定义,我得到了错误:
类型上不存在属性“$http”
我认为这与我的tsconfig.json
有关,但我不确定。请参阅以下相关文件:
src/plugins/axios.ts
import _Vue from 'vue';
import Axios from 'axios';
export function AxiosPlugin<AxiosPlugOptions>(
Vue: typeof _Vue,
options?: AxiosPluginOptions,
): void {
Vue.prototype.$http = Axios.create({
baseURL: options?.baseUrl,
});
}
export class AxiosPluginOptions {
baseUrl = '';
}
src/main.ts
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import vuetify from './plugins/vuetify';
import { AxiosPlugin } from './plugins/axios';
Vue.config.productionTip = false;
Vue.use(AxiosPlugin, {
baseUrl: 'https://localhost:44390/api/',
});
new Vue({
router,
store,
vuetify,
render: (h) => h(App),
}).$mount('#app');
tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"typeRoots": [
"./node_modules/@types",
"./node_modules/vuetify/types",
],
"types": [
"webpack-env",
"vuetify"
],
"paths": {
"@/*": [
"src/*",
],
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
有人知道为什么我的类型声明没有被识别吗?这是否回答了您的问题?我不这么认为。我正在尝试做这里描述的事情:但我无法让它按描述的那样工作。我想这与我的tsconfig定义了typeroot和types有关,所以我必须手动包含它们,但无法让它工作。这能回答你的问题吗?我不这么认为。我正在尝试做这里描述的事情:但我无法让它按描述的那样工作。我认为这与我的tsconfig定义了类型根和类型有关,所以我必须手动包含它们,但无法让它工作。
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"typeRoots": [
"./node_modules/@types",
"./node_modules/vuetify/types",
],
"types": [
"webpack-env",
"vuetify"
],
"paths": {
"@/*": [
"src/*",
],
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}