搜尋
首頁web前端Vue.jsvue3怎麼解決axios請求封裝問題

vue3怎麼解決axios請求封裝問題

May 22, 2023 pm 09:34 PM
vue3axios

vue3實戰axios請求封裝問題

1、在src目錄下建立http資料夾,並在http資料夾下分別建立index.js、request.js、api.js

# 2、index.js的作用:用於導出api.js定義的所有接口,程式碼如下

export * from './api';

3、request.js程式碼如下:

import axios from 'axios';
import buildURL from 'axios/lib/helpers/buildURL';
import { merge } from 'axios/lib/utils';

//判断指定参数是否是一个纯粹的对象,所谓"纯粹的对象",就是该对象是通过"{}"或"new Object"创建的
function isPlainObject (val) {
      return val && val.constructor.name === 'Object'
}

//请求之前进行拦截,可做的操作:1、添加loading的加载;2、添加请求头;3、判断表单提交还是json提交
let requestInterceptors = [
    config => {
        //添加loading的加载
        
        //添加请求头
        config.headers.authorization = sessionStorage.getItem('Token');
        //判断表单提交还是json提交
        if (config.emulateJSON && isPlainObject(config.data)) {
            config.data = buildURL('', config.data).substr(1);
        }
        return config;
    }
]

//请求响应之后进行拦截,可做操作:1、取消loading的加载;2、对返回状态进行判断:如请求错误、请求超时、获取数据失败、暂无数据等等
let responseInterceptors = [
    res => {
        //取消loading加载
        
        //对返回状态进行判断:如请求错误、请求超时、获取数据失败等等

        //返回结果
        return Promise.resolve(res);
    },
    err => {
        //取消loading加载
        
        //对返回状态进行判断:如请求错误、请求超时、获取数据失败等等

        //返回结果
        return Promise.reject(err);
    }
]

//组装请求
let serviceCreate = config => {
    let service = axios.create(merge({}, config));
    service.interceptors.request.use(...requestInterceptors);
    service.interceptors.response.use(...responseInterceptors);
    return service
}
serviceCreate();
export { serviceCreate, merge };

4、api.js程式碼如下:

import { serviceCreate, merge } from '@/http/request';

//这种方式可以采用单个项目的接口,也可以使用多个项目的接口,看自己的项目情况而定
let http0 = serviceCreate({
    baseURL: '/project1/api1',
    timeout: 15000,//请求超时
    emulateJSON: true,//默认表单提交
})
let http1 = serviceCreate({
    baseURL: '/project2/api2',
    timeout: 15000,//请求超时
    emulateJSON: true,//默认表单提交
})

//get请求示例
export function getData(params, config) {
    return http0.get('/project/list', merge(config, { params }));
}
//delete请求示例
export function deleteData(params, config) {
    return http0.delete('/project/list', merge(config,{ params }));
}
//post请求示例(表单提交)
export function postDataFrom(params, config) {
    return http0.post('/project/list', params, config);
}
//post请求示例(json提交)
export function postDataJson(params, config) {
    return http0.post('/project/list', params, merge(config, { emulateJSON: false }));
}
//put请求示例(表单提交)
export function putDataFrom(params, config) {
    return http0.put('/project/list', params, config);
}
//put请求示例(json提交)
export function putDataJson(params, config) {
    return http0.put('/project/list', params, merge(config, { emulateJSON: false }));
}

5、頁面中呼叫 

import { getData, deleteData, postDataFrom, postDataJson, putDataFrom, putDataJson } from "@/http";

getData({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
deleteData({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
postDataFrom({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
postDataJson({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
putDataFrom({ name: "我是参数" }).then(res => { console.log("返回数据", res) })
putDataJson ({ name: "我是参数" }).then(res => { console.log("返回数据", res) })

vue3 axios簡易封裝教學

首先在根目錄下新建utils資料夾,並在下面新建兩個文件,requests .js和html.js

requests.js用於引入axios並設定根域名以及一些預設設定、攔截器等。

import axios from "axios";

const service = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 10000,
})

// 请求拦截器
service.interceptors.request.use(config=>{
    return config
},err=>{
    return Promise.reject(err)  //返回错误
})
    
// 响应拦截器
service.interceptors.response.use(res=>{
    return res
},err=>{
    return Promise.reject(err)  //返回错误
})


export default service

寫完之後將創建的實例對象暴露出去,在html.js中進行引入

html.js檔案的作用是呼叫requests的實例對象,並將所有的存取均存放在這個文件中(api),使用的時候按需引入即可。

import request from "./requests";
export const GetPosts = () => request.get('posts/1')
export const GetsearchData = (params) => request.get('/list',{params})
export const PostPosts = (params) => request.post('posts',params)

引入的檔案:

<template>
    <el-button type="primary" @click="clickGet">点我发送get请求</el-button>
    <el-button type="primary" @click="clickPost">点我发送post请求</el-button>
    <el-button type="primary" @click="clickPut">点我发送put请求</el-button>
    <el-button type="primary" @click="clickDel">点我发送delete请求</el-button>
</template>

<script>
import { GetPosts, PostPosts } from "../../utils/html"

export default {
    setup(){
        function clickGet(){
            GetPosts().then(res => {
                console.log(res)
            })
            // axios({
            //     method: &#39;GET&#39;,
            //     url: &#39;http://localhost:3000/posts&#39;
            // }).then(res => {
            //     console.log(res)
            // })
        }
        function clickPost(){
            PostPosts({
                title: &#39;我超级喜欢打游戏&#39;,
                author: &#39;账本儿erer&#39;,
                age: &#39;24&#39;
            }).then(res => {
                console.log(res)
            })
        }
        function clickPut(){
            
        }
        function clickDel(){
            
        }
        return {
            clickDel,
            clickGet,
            clickPost,
            clickPut
        }
    }
}
</script>

<style>

</style>

以上是vue3怎麼解決axios請求封裝問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
vue.js和React:了解關鍵差異vue.js和React:了解關鍵差異Apr 10, 2025 am 09:26 AM

Vue.js適合小型到中型項目,而React更適用於大型、複雜應用。 1.Vue.js的響應式系統通過依賴追踪自動更新DOM,易於管理數據變化。 2.React採用單向數據流,數據從父組件流向子組件,提供明確的數據流向和易於調試的結構。

vue.js vs.反應:特定於項目的考慮因素vue.js vs.反應:特定於項目的考慮因素Apr 09, 2025 am 12:01 AM

Vue.js適合中小型項目和快速迭代,React適用於大型複雜應用。 1)Vue.js易於上手,適用於團隊經驗不足或項目規模較小的情況。 2)React的生態系統更豐富,適合有高性能需求和復雜功能需求的項目。

vue怎麼a標籤跳轉vue怎麼a標籤跳轉Apr 08, 2025 am 09:24 AM

實現 Vue 中 a 標籤跳轉的方法包括:HTML 模板中使用 a 標籤指定 href 屬性。使用 Vue 路由的 router-link 組件。使用 JavaScript 的 this.$router.push() 方法。可通過 query 參數傳遞參數,並在 router 選項中配置路由以進行動態跳轉。

vue怎麼實現組件跳轉vue怎麼實現組件跳轉Apr 08, 2025 am 09:21 AM

Vue 中實現組件跳轉有以下方法:使用 router-link 和 <router-view> 組件進行超鏈接跳轉,指定 :to 屬性為目標路徑。直接使用 <router-view> 組件顯示當前路由渲染的組件。使用 router.push() 和 router.replace() 方法進行程序化導航,前者保存歷史記錄,後者替換當前路由不留記錄。

vue的div怎麼跳轉vue的div怎麼跳轉Apr 08, 2025 am 09:18 AM

Vue 中 div 元素跳轉的方法有兩種:使用 Vue Router,添加 router-link 組件。添加 @click 事件監聽器,調用 this.$router.push() 方法跳轉。

vue跳轉怎麼傳值vue跳轉怎麼傳值Apr 08, 2025 am 09:15 AM

Vue 中數據傳遞有兩種主要方式:props:單向數據綁定,從父組件傳遞數據給子組件。事件:使用事件和自定義事件在組件之間傳遞數據。

vue引入方式怎麼跳轉vue引入方式怎麼跳轉Apr 08, 2025 am 09:12 AM

Vue.js提供了三種跳轉方式:原生 JavaScript API:使用 window.location.href 進行跳轉。 Vue Router:使用 <router-link> 標籤或 this.$router.push() 方法進行跳轉。 VueX:通過 dispatch action 或 commit mutation 來觸發路由跳轉。

vue怎麼設置跳轉頁面vue怎麼設置跳轉頁面Apr 08, 2025 am 09:09 AM

在 Vue 中設置頁面跳轉有多種方法,包括:使用 router-link 組件創建可點擊鏈接。使用 router.push() 方法手動添加新路由到歷史記錄堆棧。使用 router.replace() 方法替換當前路由。直接使用 location.href 重定向到新頁面。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用