接口定义
接口参数和返回值需要定义为强类型,特殊情况可以用any
import { createAPI } from '@/utils/request'
// 用户列表
export function list(params: any): Promise<any> {
return createAPI('/users', 'get', params)
}
// 用户添加
export function add(body: any): Promise<any> {
return createAPI('/users', 'post', null, body)
}
// 用户修改
export function edit(id: number, body: any): Promise<any> {
return createAPI(`/users/${id}`, 'put', null, body)
}
// 用户删除
export function remove(id: number): Promise<any> {
return createAPI(`/users/${id}`, 'delete')
}
// 用户详情
export function detail(id: number): Promise<any> {
return createAPI(`/users/${id}`, 'get')
}
组件中读取数据
// 1 导入接口包
import { list, remove } from '@/api/users'
// 2 定义接收对象
private listData: Page<User> = {
counts: 0,
page: 0,
items: [],
pages: 0,
pagesize: 0
}
// 3 采用 promise 方式读取
private async getList() {
const { data } = await list()
this.listData = data
}
request 参考
采用 axios 二次封装,更多处理你可以在 interceptors
中实现。
import axios, { AxiosRequestConfig, Method } from 'axios'
import { Message /*, MessageBox*/ } from 'element-ui'
import { getToken } from '@/utils/cookies'
const service = axios.create({
baseURL: '/api',
timeout: 5000 * 5
})
service.defaults.headers.post['Content-Type'] = 'application/json'
// Request interceptors
service.interceptors.request.use(
config => {
const token = getToken()
if (token) {
config.headers['Authorization'] = token
}
return config
},
error => {
Promise.reject(error)
}
)
// Response interceptors
service.interceptors.response.use(
response => response,
error => {
Message({
message: error.response.data.errMessage || error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export const createAPI = (
url: string,
method: Method = 'get',
params: any = undefined,
data: any = undefined
) => {
const config: AxiosRequestConfig = {}
config.url = url
config.method = method
if (params !== undefined) {
config.params = params
}
if (method != 'get' && data !== undefined) {
config.data = data
}
return service(config)
}
export const createFormAPI = (url: string, method: Method, data: any) => {
const config: AxiosRequestConfig = {}
config.url = url
config.method = method
config.data = data
config.headers = {
'Cache-Control': 'no-cache',
// 'Content-Type': 'application/x-www-form-urlencoded'
'Content-Type': 'multipart/form-data'
}
// config.responseType = 'json'
// config.transformRequest = [
// function(data) {
// let ret = ''
// for (let it in data) {
// ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
// }
// return ret
// }
// ]
return service(config)
}
export default service