vue封装API接口

第一步:

首先引入axios

然后创建两个文件夹api和http

 

http.js 里面的

 1 import axios from 'axios';//引入axios
 2  
 3 //环境的切换 开发环境(development)使用的是测试接口  和   生产环境(production)使用的是上线接口
 4 if(process.env.NODE_ENV=='development'){
 5     //设置默认路径
 6     axios.defaults.baseURL='http://120.53.31.103:84/'
 7 }
 8 if(process.env.NODE_ENV=='production'){
 9     axios.defaults.baseURL='https://wap.365msmk.com/'
10 }
11 axios.defaults.timeout=5000;//加载不出来5秒之后就是加载失败
12 axios.interceptors.request.use(
13     config=>{
14         config.headers={DeviceType:'H5'}//可每次发送请求之前的逻辑处理 比如判断token
15         return config;
16     }
17 )
18 // axios.interceptors.response.use(
19 //     response=>{
20 //       return response;
21 //     },
22 //     error=>{
23 //         if(error.response.status){
24 
25 //         }
26 //     }
27 // )
28 
29 // 使用promise返回axios请求的结果
30 export function get(url, params) {
31         return new Promise((resolve, reject) => {
32             axios.get(url, {
33                 params:params
34             }).then(res => {
35                 resolve(res)
36             }).catch(err => {
37                 reject(err)
38             })
39         })
40     };
41     
42     export function post(url,params){
43         return new Promise((resolve,reject)=>{
44             axios.post(url,params).then(res=>{
45                 resolve(res.data)
46             }).catch(err=>{
47                 reject(err.data)
48             })
49     
50         })
51     }  

api.js里面的

import { get, post } from "../http/http" //引入封装好的get和post方法
// 封装请求的方式
export function getBanners() {//轮播
    return get('api/app/banner')
}

export function getIndex(){//首页数据
    return get('api/app/recommend/appIndex')
}

然后在vue里面的文件应用


import { getBanners, getIndex } from "../api/api";//引入api里面定义的方法


async mounted() { var swiperr
= await getBanners(); console.log(swiperr.data.data); this.swipers = swiperr.data.data; //轮播图渲染 var strr = await getIndex(); console.log(strr); //明星讲师渲染 this.strs = strr.data.data; console.log(this.strs); },

 

 然后就没有然后了

posted @ 2020-10-07 15:31  井九。  阅读(3070)  评论(0编辑  收藏  举报