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); },

 

 然后就沒有然后了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM