1、创建http.js 引入axios 配置axios import axios from "axios"; import qs from "qs"; var http = axios.create({ // baseURL:"XXXX", timeout:5000 }) //请求拦截 http.interceptors.request.use((config)=>{ // if(config.method == "post"){ // config.data = qs.stringify(config.data); // } return config; },(err)=>{ return Promise.reject(err) }) //响应拦截 http.interceptors.response.use((res)=>{ return res.data },(err)=>{ return Promise.reject(err) }) export default (method,url,data = null)=>{ if(method == "post"){ return http.post(url,data); }else if(method == "get"){ return http.get(url,{params:data}) }else{ return; } }
2、在api文件夹下引入http.js.简单用info.js为例 import http from "./http.js"; //在这里定义了一个登陆的接口,把登陆的接口暴露出去给组件使用 export const login = params=>http("post","/user/login",params); export const register = params=>http("get","/user/register",params);
3、在组件中使用 import {homeData} from "../../apis/home"; export default { async handleData(){ let data = await homeData() console.log(data) } }