最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Vue二次封裝axios流程詳解

 更新時間:2022年10月27日 15:20:09   作者:小白探索世界歐耶!~  
在vue項目中,和后臺交互獲取數(shù)據(jù)這塊,我們通常使用的是axios庫,它是基于promise的http庫,下面這篇文章主要給大家介紹了關(guān)于Vue3引入axios封裝接口的兩種方法,需要的朋友可以參考下

一、為什么要封裝axios

api統(tǒng)一管理,不管接口有多少,所有的接口都可以非常清晰,容易維護。

通常我們的項目會越做越大,頁面也會越來越多,如果頁面非常的少,直接用axios也沒有什么大的影響,那頁面組件多了起來,上百個接口呢,這個時候后端改了接口,多加了一個參數(shù)什么的呢?那就只有找到那個頁面,進去修改,整個過程很繁瑣,不易于項目的維護和迭代。

這個時候如果我們統(tǒng)一的區(qū)管理接口,需要修改某一個接口的時候直接在api里修改對應(yīng)的請求,是不是很方便呢?因為我們用的最多的還是get post請求,我們就可以針對封裝。

二、怎么封裝axios

1. 拿到項目和后端接口,首先要配置全局代理;

2. 接著全局封裝axios和request.js;

3. 過濾axios請求方式,控制路徑,參數(shù)的格式,http.js;

4. 正式封裝api.js;

5. 頁面調(diào)用;

三、具體步驟

vue項目的前期配置

1. 終端輸入

npm i axios -S

2. 在項目中 main.js 文件中輸入

import axios from "axios";

配置config文件中的代理地址

修改項目中config目錄下的index.js文件?!疽部赡苁莢ue.config.js 文件】

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        pathRewrite: {
          '^/': ''
        }
      },
      '/ws/*': {
        target: 'ws://127.0.0.1:8080',
        ws: true
      }
    },
    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8082, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: true,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,
    /**
     * Source Maps
     */
    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',
    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,
    cssSourceMap: true
  },
  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),
    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    /**
     * Source Maps
     */
    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

封裝axios實例-request.js

/****   request.js   ****/
// 導(dǎo)入axios
import axios from 'axios'
// 使用element-ui Message做消息提醒
import { Message} from 'element-ui';
//1. 創(chuàng)建新的axios實例,
const service = axios.create({
  // 公共接口--這里注意后面會講
  baseURL: process.env.BASE_API,
  // 超時時間 單位是ms,這里設(shè)置了3s的超時時間
  timeout: 3 * 1000
})
// 2.請求攔截器
service.interceptors.request.use(config => {
  //發(fā)請求前做的一些處理,數(shù)據(jù)轉(zhuǎn)化,配置請求頭,設(shè)置token,設(shè)置loading等,根據(jù)需求去添加
  config.data = JSON.stringify(config.data); //數(shù)據(jù)轉(zhuǎn)化,也可以使用qs轉(zhuǎn)換
  config.headers = {
    'Content-Type':'application/json' //配置請求頭
  }
  //如有需要:注意使用token的時候需要引入cookie方法或者用本地localStorage等方法,推薦js-cookie
  //const token = getCookie('名稱');//這里取token之前,你肯定需要先拿到token,存一下
  //if(token){
  //config.params = {'token':token} //如果要求攜帶在參數(shù)中
  //config.headers.token= token; //如果要求攜帶在請求頭中
  //}
  return config
}, error => {
  Promise.reject(error)
})
// 3.響應(yīng)攔截器
service.interceptors.response.use(response => {
  //接收到響應(yīng)數(shù)據(jù)并成功后的一些共有的處理,關(guān)閉loading等
  return response
}, error => {
  /***** 接收到異常響應(yīng)的處理開始 *****/
  if (error && error.response) {
    // 1.公共錯誤處理
    // 2.根據(jù)響應(yīng)碼具體處理
    switch (error.response.status) {
      case 400:
        error.message = '錯誤請求'
        break;
      case 401:
        error.message = '未授權(quán),請重新登錄'
        break;
      case 403:
        error.message = '拒絕訪問'
        break;
      case 404:
        error.message = '請求錯誤,未找到該資源'
        window.location.href = "/NotFound"
        break;
      case 405:
        error.message = '請求方法未允許'
        break;
      case 408:
        error.message = '請求超時'
        break;
      case 500:
        error.message = '服務(wù)器端出錯'
        break;
      case 501:
        error.message = '網(wǎng)絡(luò)未實現(xiàn)'
        break;
      case 502:
        error.message = '網(wǎng)絡(luò)錯誤'
        break;
      case 503:
        error.message = '服務(wù)不可用'
        break;
      case 504:
        error.message = '網(wǎng)絡(luò)超時'
        break;
      case 505:
        error.message = 'http版本不支持該請求'
        break;
      default:
        error.message = `連接錯誤${error.response.status}`
    }
  } else {
    // 超時處理
    if (JSON.stringify(error).includes('timeout')) {
      Message.error('服務(wù)器響應(yīng)超時,請刷新當前頁')
    }
    error.message = '連接服務(wù)器失敗'
  }
  Message.error(error.message)
  /***** 處理結(jié)束 *****/
  //如果不需要錯誤處理,以上的處理過程都可省略
  return Promise.resolve(error.response)
})
//4.導(dǎo)入文件
export default service

四、封裝請求-http.js

/****   http.js   ****/
// 導(dǎo)入封裝好的axios實例
import request from './request'
const http ={
  /**
   * methods: 請求
   * @param url 請求地址
   * @param params 請求參數(shù)
   */
  get(url,params){
    const config = {
      method: 'get',
      url:url
    }
    if(params) config.params = params
    return request(config)
  },
  post(url,params){
    const config = {
      method: 'post',
      url:url
    }
    if(params) config.data = params
    return request(config)
  },
  put(url,params){
    const config = {
      method: 'put',
      url:url
    }
    if(params) config.params = params
    return request(config)
  },
  delete(url,params){
    const config = {
      method: 'delete',
      url:url
    }
    if(params) config.params = params
    return request(config)
  }
}
//導(dǎo)出
export default http

五、正式封裝API用于發(fā)送請求-api.js

import request from "@/utils/request.js";
import qs from "qs";
const baseUrl = '/api/jwt/auth'
//登錄
export function authCodeLogin(params) {
  return request({
    url: baseUrl + "/authCodeLogin/" + params.code,
    method: "get",
  });
}
//退出
export function authLogout(params) {
  return request({
    url: baseUrl + "/logout",
    method: "get",
  });
}
//獲取用戶數(shù)據(jù)
export function getUserInfo(params) {
  return request({
    url: baseUrl + "/getUserInfo",
    method: "get",
    params:qs.stringfy(params)
  });
}
//其實,也不一定就是params,也可以是 query 還有 data 的呀!
//params是添加到url的請求字符串中的,用于get請求。會將參數(shù)加到 url后面。所以,傳遞的都是字符串。無法傳遞參數(shù)中含有json格式的數(shù)據(jù)
//而data是添加到請求體(body)中的, 用于post請求。添加到請求體(body)中,json 格式也是可以的。

六、如何在vue文件中調(diào)用

用到哪個api 就調(diào)用哪個接口

import { authCodeLogin  } from '@/api/api.js'
   getModellogin(code){
      let params = {
        code: code,
      }
      authCodeLogin(params).then(res=>{
        if (res.code === 200) {
          localStorage.clear()
          // 菜單
          this.$store.dispatch('saveMenu', [])
          // this.getFloorMenu()
          // this.getmenu()
          this.$router.push('/')
        }else{
          console.log('error');
        }
      })
    },

到此這篇關(guān)于Vue二次封裝axios流程詳解的文章就介紹到這了,更多相關(guān)Vue封裝axios內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Pycharm中開發(fā)vue?element項目時eslint的安裝和使用步驟

    Pycharm中開發(fā)vue?element項目時eslint的安裝和使用步驟

    這篇文章主要介紹了Pycharm中開發(fā)vue?element項目時eslint的安裝和使用,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-05-05
  • 如何在Vue3項目中操作MySQL數(shù)據(jù)庫

    如何在Vue3項目中操作MySQL數(shù)據(jù)庫

    在Vue3項目中使用axios發(fā)送HTTP請求與后端MySQL數(shù)據(jù)庫交互的步驟:1. 安裝MySQL數(shù)據(jù)庫并創(chuàng)建數(shù)據(jù)庫表;2. 后端服務(wù)器使用Node.js的mysql模塊實現(xiàn)MySQL數(shù)據(jù)庫操作接口;3. Vue3項目中使用axios調(diào)用這些接口進行數(shù)據(jù)交互
    2024-11-11
  • 如何修改el-form-item 的label的字體顏色

    如何修改el-form-item 的label的字體顏色

    這篇文章主要介紹了如何修改el-form-item 的label的字體顏色問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • vue項目打包之后背景樣式丟失的解決方案

    vue項目打包之后背景樣式丟失的解決方案

    今天小編就為大家分享一篇關(guān)于vue項目打包之后背景樣式丟失的解決方案,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • Vue通過vue-router實現(xiàn)頁面跳轉(zhuǎn)的全過程

    Vue通過vue-router實現(xiàn)頁面跳轉(zhuǎn)的全過程

    這篇文章主要介紹了Vue通過vue-router實現(xiàn)頁面跳轉(zhuǎn)的操作步驟,文中有詳細的代碼示例和圖文供大家參考,對大家的學習或工作有一定的幫助,感興趣的朋友可以參考下
    2024-04-04
  • Vue?element-ui中表格過長內(nèi)容隱藏顯示的實現(xiàn)方式

    Vue?element-ui中表格過長內(nèi)容隱藏顯示的實現(xiàn)方式

    在Vue項目中,使用ElementUI渲染表格數(shù)據(jù)時,如果某一個列數(shù)值長度超過列寬,會默認換行,造成顯示不友好,下面這篇文章主要給大家介紹了關(guān)于Vue?element-ui中表格過長內(nèi)容隱藏顯示的實現(xiàn)方式,需要的朋友可以參考下
    2022-09-09
  • Vue3中emit傳值的具體使用

    Vue3中emit傳值的具體使用

    Emit是Vue3中另一種常見的組件間傳值方式,它通過在子組件中觸發(fā)事件并將數(shù)據(jù)通過事件參數(shù)傳遞給父組件來實現(xiàn)數(shù)據(jù)傳遞,本文就來介紹一下Vue3 emit傳值,感興趣的可以了解一下
    2023-12-12
  • vue滑動解鎖組件使用方法詳解

    vue滑動解鎖組件使用方法詳解

    這篇文章主要為大家詳細介紹了vue滑動解鎖組件的使用方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • vue-cli項目優(yōu)化方法- 縮短首屏加載時間

    vue-cli項目優(yōu)化方法- 縮短首屏加載時間

    這篇文章主要介紹了vue-cli項目優(yōu)化 縮短首屏加載時間,需要的朋友可以參考下
    2018-04-04
  • vue3實現(xiàn)長列表虛擬滾動的示例代碼

    vue3實現(xiàn)長列表虛擬滾動的示例代碼

    本文主要介紹了vue3實現(xiàn)長列表虛擬滾動的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2025-01-01

最新評論

济源市| 陆川县| 灵台县| 滨州市| 博爱县| 崇文区| 昭平县| 岢岚县| 阳谷县| 临泽县| 高要市| 东丽区| 长泰县| 石景山区| 德令哈市| 海淀区| 土默特左旗| 宕昌县| 南京市| 商城县| 崇明县| 如东县| 横峰县| 临清市| 宜丰县| 南丹县| 双峰县| 萍乡市| 花莲县| 宣化县| 崇州市| 阳春市| 罗源县| 宝坻区| 普宁市| 邢台县| 仲巴县| 嘉定区| 常德市| 囊谦县| 通道|