前言
普通得Axios使用起来比较麻烦,不便于管理,就需要封装网络请求,减少繁琐步骤,封装最终效果,根据类别将网络请求封装在文件中,使用得时候调用文件名名称加文件中得自定义名称,就可以了
需要vue2Axios封装网络请求得点这里
需要Axios+小程序封装网络请求的点这里
安装Axios
npm install axios
或者
yarn add axios
新建network文件,
index.ts:网络请求得封装
apis:网络请求得总文件
home.ts:自定义名称,根据网络请求类型活类编进行起名
index.ts
// 导入axios网络请求
import axios from "axios"
import router from "@/router";
// import Vue from 'vue'
const service = axios.create({
baseURL: "/api",//接口请求头
timeout: 40000,
headers: {
"Access-Control-Allow-Origin": "*",
"Connection": "Keep-Alive",
"Content-Type": "application/json; charset = utf-8"
}
})
//请求拦截
service.interceptors.request.use(
config => {
const token = localStorage.getItem("token");
if (token) {
config.headers["access-token"] = token
}
return config;
}
)
// 响应拦截
service.interceptors.response.use(
(res) => {
const code = res.data.code // 获取后端返回的状态码
if (code == 100) {
router.push({ name: "login" });
}
return res
}, (error) => {
return Promise.reject(error);
}
)
function startNetwork(params: any) {
return service({
...params,
});
}
const modules = require.context("./apis", true, /\.(js|ts)$/);
const newModules = modules.keys().reduce((target: any, keyName) => {
const fileName = keyName.replace(/^\.\/(\w+)\.(js|ts)$/, "$1");
const module = modules(keyName).default;
for (const key in module) {
target[fileName + "/" + key] = module[key];
}
return target;
}, {});
//遍历newModules中的键值对,为key添加getter方法
const proxy = new Proxy(newModules, {
async get(target, keyName) {
const params = target[keyName](target.meta ? target.meta : {});
const data = await startNetwork(params);
target.meta = null;
return data;
}
});
async function getData<T = any>(keyName: string, meta: Record<string, any> | null = null): Promise<T> {
// 检查 keyName 是否存在
if (!(keyName in proxy)) {
throw new Error(`Key "${keyName}" does not exist in the proxy object.`);
}
// 如果 meta 存在,设置到 proxy.meta
if (meta) {
proxy.meta = meta;
}
try {
// 调用 proxy[keyName] 并返回结果
const result = await proxy[keyName];
return result;
} catch (error) {
console.error(`Error occurred while fetching data for key "${keyName}":`, error);
throw error; // 抛出错误以便调用方处理
}
}
export default getData;
home.ts
export default {
//
PostXq(params: any) {//自定义名称,根据请求数据进行起名,一个文件中名称不可以不可以重复
return {
method: "POST",
url: "",//这里写下你的请求头后边得内容
params,
};
},
// / 首页数据
GetIndex(params: any) {
return {
method: "GET",
url: "",
params,
};
},
}
使用方式
那个页面使用,就在那个页面中引入,getDatas ,
然后将网络请求写成对应得函数即可,使用时候调用对应得函数,就可以调用网络请求,使用得时候只需要调用该文件下的对应得请求即可进行网络请求
<script lang="ts" setup>
import getDatas from "@/network/index";
</script>
需要传参数
home:apis文件下的文件
PostXq:home文件下的起的自定义名称
const PostXq= async () => {
const res = await getDatas("home/PostXq", {
title: search.value,
status: '',
page: currentPage.value,
limit: pageSize.value,
});
console.log("PostXq", JSON.parse(JSON.stringify(res.data)));
if (res.data.code == 0) {
tableData.value = res.data.lists;
totle.value = res.data.totle_num;
}else {
ElMessage.error(res.data.msg);
}
};
不传参数
const GetIndex= async () => {
const res = await getDatas("home/GetIndex");
console.log("GetIndex", JSON.parse(JSON.stringify(res.data)));
if (res.data.code == 0) {
tableData.value = res.data.lists;
}else {
ElMessage.error(res.data.msg);
}
};
补充:vue.config.js中设置请求地址以及跨域
将这段代码放入你的vue.config.js中
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
outputDir: 'dist',
assetsDir: 'assets',
lintOnSave: false,
devServer: {
port: 8086,
open: true,
proxy: {
"/api": {
target: "",//放你的请求地址
changeOrigin: true,
secure: false,
ws: false,
// pathRewrite: {
// "^/api": "",
// },
},
}
},
})