使用Vue+ts开发项目时,定义了一个ApiReq类用于api的访问。但无法在*.vue文件中引用,使用js作为文件结尾却可以引用,把代码贴出来大家看一下。
- 文件目录
- api/index.ts
import axios, { AxiosInstance, AxiosPromise } from 'axios';
const API_URLS = {
user : {
get : '/tslint.json',
post : '/tslint.json',
put : '/tslint.json',
delete: '/tslint.json'
},
list : {
get : '/tslint.json',
post : '/tslint.json',
put : '/tslint.json',
delete: '/tslint.json'
},
article: {
get : '/tslint.json',
post : '/tslint.json',
put : '/tslint.json',
delete: '/tslint.json'
}
};
export default class ApiReq {
model: string;
method: string;
data?: object;
connection?: AxiosInstance;
constructor (model: string, method: string, data?: object) {
this.model = model;
this.method = method;
this.data = data;
this.connection = axios.create({
baseURL: '/',
timeout: 30000
});
}
pull (): AxiosPromise {
if (Object.getOwnPropertyNames(API_URLS).filter(item => (item === this.model)).length <= 0) {
return null;
}
this.method = this.method || 'get';
if (['get', 'post', 'put', 'delete'].filter(item => (item === this.method)).length <= 0) {
return null;
}
this.data = this.data || {};
switch (this.method) {
case 'get':
let str = '?';
Object.getOwnPropertyNames(this.data).filter(function (val) {
str += `${val}=${this.data[val]}&`;
return true;
});
return this.connection.get(`${API_URLS[this.model][this.method]}${str}`);
case 'post':
return this.connection.post(API_URLS[this.model][this.method], this.data);
case 'put':
return this.connection.put(API_URLS[this.model][this.method], this.data);
case 'delete':
return this.connection.delete(API_URLS[this.model][this.method]);
}
}
}
*login.vue
<template>
<div class="LoginTemplate">
<h1 @click="onClick">{{message}}</h1>
<Test :my="message"></Test>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import Test from './test.vue'
/*这一句引入*/import ApiReq from '../../api/index';
// @Component 修饰符注明了此类为一个 Vue 组件
@Component({
components: {
Test: Test
}
})
export default class Login extends Vue {
// 初始数据可以直接声明为实例的属性
message: string = 'Hello!';
// 组件方法也可以直接声明为实例的方法
onClick (str: any): void {
this.my();
console.log(str);
}
my (): void {
new ApiReq('user', 'get').pull().then(function (data) {
console.log(data);
}).catch(function (e) {
console.log(e);
});
}
}
</script>
<style scoped>
h1,
h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
*报错信息
ERROR Failed to compile with 1 errors 19:21:29
This relative module was not found:
* ../../api/index in ./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0&bustCache!./src/components/public/login.vue
安装file-loader