1. 程式人生 > 程式設計 >Vue專案中如何封裝axios(統一管理http請求)

Vue專案中如何封裝axios(統一管理http請求)

1、需求說明

在使用vue.js框架開發前端專案時,會經常傳送ajax請求服務端介面,在開發過程中,需要對axios進一步封裝,方便在專案中的使用。

2、Vue專案結構

在本地建立Vue專案,目錄結構如下:

&nb程式設計客棧sp;- public靜態資原始檔
- src
|- assets靜態資源目錄
|- components公共元件目錄
|- httpaxios封裝目錄
|- router路由管理目錄
|- store狀態管理目錄
|- views檢視元件目錄
|- App.vue根元件
|- main.js入口檔案
- package.jsonnpm配置檔案

在Vue專案中建立 http目錄 作為axios的管理目錄,在 http目錄 下兩個檔案,分別是

  • /http/index.js 封裝axios方法的檔案
  • /http/api.js 統一管理介面的檔案

3、程式碼示例

/http/api.js檔案程式碼如下:

export default {
    'users_add': '/users/add','users_find': '/users/find','users_update': '/users/update','users_delete': '/users/delete'
}

/程式設計客棧http/index.js檔案程式碼如下:

import axios from 'axios'
import api from './api'

//建立axios例項物件
let instance = axios.create({
    baseURL: 'http://localhost:3000',//伺服器地址
    timeout: 5000 //預設超時時長
})

//請求攔截器
instance.interceptors.request.use(config=>{
    //此處編寫請求攔截的程式碼,一般用於彈出載入視窗
    console.log('正在請求……')
    return config
},err=>{
    console.error('請求失敗',err)
})

//響應攔截器
instance.interceptors.response.use(res=>{
    //此處對響應資料做處理
    console.log('請求成功!')
    return res //該返回物件會傳到請求方法的響應物件中
},err=>{
    // 響應錯誤處理
    console.log('響應失敗!',err)
    // return Promise.reject(err);
})

//封裝axios請求方法,引數為配置物件
//option = {method,url,params} method為請求方法,url為請求介面,params為請求引數
async function http(option = {}) {
    let result = null
    if(option.method === 'get' || option.method === 'delete'){
     //處理get、delete請求
        await instance[option.method](
                api[option.url],{params: option.params}
          ).then(res=>{
            result = res.data
        }).catch(err=>{
            result = err
        })
    }else if(option.method === 'post' || option.method === 'put'){
     //處理post、put請求
        await inszLkfENSon
tance[option.method]( api[option.url],option.params ).then(res=>{ result = res.data }).catch(err=>{ result = err }) } return result } export default 程式設計客棧http

在main.js入口檔案中引入封裝好的 /http/index.js 檔案,示例程式碼如下:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import http from './http'

Vue.config.productionTip = false
VuezLkfENSon
.prototype.$http = http Vue.use(Elementui) new Vue({ router,store,render: h => h(App) }).$mount('#app')

在App.vue根元件中測試axios請求,示例程式碼如下:

<template>
  <div>
    <button @click="getDate">傳送請求</el-button>
  </div>
</template>

<script>
export default {
  methods: {
    getDate(){
      this.$http({
        method: 'get',url: 'users_find'
      }).then(res=>{
        console.log(res)
      })

    }
  }
}
</script>

這裡需要有 http://localhost:3000/users/find 介面,不然請求會失敗!

4、效果演示

啟動Vue專案,在瀏覽器中訪問Vue專案的地址,我的地址是 http://localhost:8080,點選按鈕傳送請求,獲取的結果如下圖所示。

到此,在Vue專案中就完成了簡單的axios封裝,你也可以根據自己的實際需求對axios進行封裝,本文只是提供參考。

到此這篇關於Vue專案中如何封裝axios(統一管理http請求)的文章就介紹到這了,更多相關Vue封裝axios管理http請求內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!