Vue全局封装Axios,配置公共方法
1、安装axios:
npm install axios
2、新建文件夹并添加:
VUE_APP_BASE_API = http://localhost:5000/api/
3、封装axios
新建文件夹net,net下新建api和request.js
request.js 设置请求地址,header类型,出错提示
import axios from 'axios' const service = axios.create({ baseURL:process.env.VUE_APP_BASE_API, timeout: 30000 }) service.interceptors.request.use(config=>{ if(config.method.toUpperCase()=="POST"){ config.headers['Content-Type'] = 'application/json' } return config }, error=>{ Notification({ title:'Error', message:'网络出现异常,请按下F5 重试', showClose:true }) Promise.reject(error) }) service.interceptors.response.use( response => response, error => { return Promise.reject(error) }) export default service
api下新建base.js: 公共方法
import request from "../request"; /** * 公共的添加方法 * @param {实体对象} entity * @returns */ export function add(type, entity) { return request({ url: `${type}/Add`, method: "post", data: entity, }); } export function get(type) { return request({ url: `${type}`, method: "get" }); } export function upload(type,entity) { return request({ url: `${type}/Post`, method: "post", data:entity }); } export function postData(type,entity) { return request({ url: `${type}`, method: "post", data:entity }); }
封装公共方法:
1、新建:
2、serviceMixin.js //所有方法
import { add } from "../net/api/base"; import { get } from "../net/api/base"; import { upload } from "../net/api/base"; import { postData } from "../net/api/base"; export default { methods: { async addEntity(type, entityObject) { return await add(type, entityObject); }, async getDatas(type) { return await get(type); }, async uploadFile(type, entityobject) { return await upload(type, entityobject); }, async postData(type, entityobject) { return await postData(type, entityobject); }, }, };
全局调用方式:
引用:
import serviceMixin from "../mixins/seviceMixin";
methods: { async LoadData() { this.getDatas("Project").then((res) => { this.projectLogsArray = res.data.items; console.log(this.projectLogsArray); }); }, }