promise封裝axios方法

axios

  • 獲取后臺數(shù)據(jù)的方法插件

promise

  • 處理異步的方法

封裝

  • 在實際項目里為了更方便的使用axios獲取后臺數(shù)據(jù),這里我們用promise封裝一下
    vue項目里封裝方法我們一般放在utils文件夾里
    src下新建一個utils文件夾,index.js文件
/* eslint-disable no-unused-vars */
import axios from 'axios';


// const get = () => {
//     console.log('get請求');
// }

// const post = () => {
//     console.log('post請求')
// }

// export{
//     get,
//     post
// }

// process.env.NODE_ENV環(huán)境
let baseURL;
if(process.env.NODE_ENV=='development'){
    baseURL = 'http://132.232.94.151:3000/api'
}else{
    baseURL = '/xxx'
}
// baseURL es6 方法


const $http = axios.create({
    baseURL,
})
// create 是axios自帶的方法

export const get = (url,params)=>{
    params = params || {};
    return new Promise((resolve,reject)=>{
        // axiso 自帶 get 和 post 方法
        $http.get(url,{
            params,
        }).then(res=>{
            if(res.data.status===0){
                resolve(res.data);
            }else{
                alert(res.data.msg)
            }
        }).catch(error=>{
            alert('網(wǎng)絡(luò)異常');
        })
    })
}

export const post = (url,params)=>{
    params = params || {};
    return new Promise((resolve,reject)=>{
        $http.post(url,params).then(res=>{
            if(res.data.status===0){
                resolve(res.data);
            }else{
                alert(res.data.msg);
            }
        }).catch(error=>{
            alert('網(wǎng)絡(luò)異常');
        })
    })
}

這里用到了的知識點
1.baseURL
2.axios的create方法
3.promise以及axios的get和post

main.js方面

import { get, post } from "./utils/index";
Vue.prototype.$http = {
  get,
  post
};

1.這里使用了構(gòu)造函數(shù)的原型prototype(vue屬于構(gòu)造函數(shù))
2.聲明一個全局變量并且把封裝好的get和post方法放在里面
使用封裝后的函數(shù)

  created() {
    this.getFilmList();
  },
  methods: {
    async getFilmList() {
      const url = "/film/getList";
      // 要訪問第二頁的話在網(wǎng)址后面加 ?type=2&pageNum=頁數(shù)
      const res = await this.$http.get(url);
      this.filmList = res.films;
    },

這里注意的是,因為是promise封裝的函數(shù)方法,所以使用的時候要加上
async 函數(shù)(){ await 數(shù)據(jù)} 不然會報錯,因為沒有完成異步轉(zhuǎn)同步

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容