npm install axios --save
在src/utils文件夹下新建axios.js文件:
import axios from 'axios';
//设置axios
const service=axios.create({
timeout: 1000*60,
baseURL:'',//对axios发送的请求路径进行集中设置
// baseURL:'/api',//对axios发送的请求路径进行集中设置
//意思是在接口路径前加上/api
//这里的 /api 是和vue.config.js中proxy 中设置的对应
})
//封装post请求
let post=function(url,data_={}){
return new Promise((resolve,reject)=>{
service.post(url, data_).then((res) => {
console.log('post res', res);
return resolve(res)
}).catch((err)=>{
return reject(err)
})
})
}
//封装get请求
let get=function(url,params){
return new Promise((resolve,reject)=>{
service.get(url,{params}).then((res)=>{
console.log('get res', res);
return resolve(res)
}).catch((err)=>{
return reject(err)
})
})
}
//请求拦截
service.interceptors.request.use(config=>{
//添加请求头
config.headers={
"Authorization":localStorage.token
}
return config
},err=>{
return Promise.reject(err)
})
//添加响应拦截
service.interceptors.response.use(res=>{
return res.data
},err=>{
return err
})
export default{
post,
get
}
1、在src中新建api文件
2、在api文件夹中新建文件,最好每个页面的接口写一个文件
import axios from '@/utils/axios'
export function getDepartmentsList (data) {
return axios.post('/vue-table-list/tableLinkage/list', data)
}
export function geBasicAccountType(data) {
return axios.get('/sys/dict/basic_account_type', data)
}
PS:若使用mockjs,直接让mock的url与api文件下的接口一致就好,如/sys/dict/basic_account_type:
const Mock = require('mockjs')
const basic_account_type = [
{
"remark": null,
"dictCode": 1280,
"dictSort": 1,
"dictLabel": "银行帐号",
"dictValue": "1",
"status": "1",
},
{
"remark": null,
"dictCode": 1281,
"dictSort": 2,
"dictLabel": "虚拟子户",
"dictValue": "2",
"status": "1",
}
]
// mock模拟的接口
Mock.mock('/sys/dict/basic_account_type', 'get', function () {
return {
"msg": "操作成功",
"code": 200,
data: basic_account_type
}
})
// 引入接口
import {
getDepartmentsList
} from '@/api/tableLinkage'
// 接口使用
getList () {
this.tableLoading = true
getDepartmentsList(this.queryParams).then(res => {
this.tableData = res?.rows || []
this.total = res?.total || 0
this.tableLoading = false
}).catch(() => { this.tableLoading = false })
},