实战教程vite+vue3.0+ts中如何封装axios?(vue怎么封装axios)
admin148856年前0条评论
对于于vue中应用axios的作为前端以及后端接口交互工具的用法文章,收集某博客上不可胜数。因为名目从0到1最先需要基于vite+vue3.0+ts中封装axios,以是今天让小编来给人人布置axios整合vite+vue3.0+ts的细致封装步调。记载一下自身封装步调,随着我的措施,撸起来。。。
一、布置axios
- npm i axios
细致:这里的布置命令便是默认布置最新版本的axios
二、封装申请同伴代码提醒error-code-type.ts
代码下列:
- export const errorCodeType = function(code:string):string{
- let errMessage:string = "未知同伴"
- switch (code) {
- case 400:
- errMessage = '同伴的申请'
- break
- case 401:
- errMessage = '未授权,请从新登录'
- break
- case 403:
- errMessage = '推辞访问'
- break
- case 404:
- errMessage = '申请同伴,未找到该资本'
- break
- case 405:
- errMessage = '申请方法未许可'
- break
- case 408:
- errMessage = '申请超时'
- break
- case 500:
- errMessage = '效劳器端失足'
- break
- case 501:
- errMessage = '收集未实现'
- break
- case 502:
- errMessage = '收集同伴'
- break
- case 503:
- errMessage = '效劳不可用'
- break
- case 504:
- errMessage = '收集超时'
- break
- case 505:
- errMessage = 'http版本不反对于该申请'
- break
- default:
- errMessage = `其余连接同伴 --${code}`
- }
- return errMessage
- }
三、封装request.ts
这里用到的element-plus人人能够参考其官网布置就可,传递门:element-plus官网
布置命令:
- npm install element-plus --save
代码下列:
- import axios from 'axios';
- import { errorCodeType } from '@/script/utils/error-code-type';
- import { ElMessage, ElLoading } from 'element-plus';
-
- // 建立axios实例
- const service = axios.create({
- // 效劳接口申请
- baseURL: import.meta.env.VITE_APP_BASE_API,
- // 超时配置
- // timeout: 15000,
- headers:{'Content-Type':'application/json;charset=utf-8'}
- })
-
- let loading:any;
- //正在申请的数目
- let requestCount:number = 0
- //显示loading
- const showLoading = () => {
- if (requestCount === 0 && !loading) {
- //加载中显示样式能够自行修改
- loading = ElLoading.service({
- text: "冒去世加载中,请稍后...",
- background: 'rgba(0, 0, 0, 0.7)',
- spinner: 'el-icon-loading',
- })
- }
- requestCount++;
- }
- //隐蔽loading
- const hideLoading = () => {
- requestCount--
- if (requestCount == 0) {
- loading.close()
- }
- }
-
- // 申请拦截
- service.interceptors.request.use(config => {
- showLoading()
- // 是否需要配置 token放在申请头
- // config.headers['Authorization'] = 'Bearer ' + getToken() // 让每一个申请照顾自界说token 请依据实践状况自行修改
- // get申请照射params参数
- if (config.method === 'get' && config.params) {
- let url = config.url + '?';
- for (const propName of Object.keys(config.params)) {
- const value = config.params[propName];
- var part = encodeURIComponent(propName) + "=";
- if (value !== null && typeof(value) !== "undefined") {
- // 工具解决
- if (typeof value === 'object') {
- for (const key of Object.keys(value)) {
- let params = propName + '[' + key + ']';
- var subPart = encodeURIComponent(params) + "=";
- url += subPart + encodeURIComponent(value[key]) + "&";
- }
- } else {
- url += part + encodeURIComponent(value) + "&";
- }
- }
- }
- url = url.slice(0, -1);
- config.params = {};
- config.url = url;
- }
- return config
- }, error => {
- console.log(error)
- Promise.reject(error)
- })
-
- // 响应拦截器
- service.interceptors.response.use((res:any) => {
- hideLoading()
- // 未配置状态码则默认胜利状态
- const code = res.data['code'] || 200;
- // 获取同伴信息
- const msg = errorCodeType(code) || res.data['msg'] || errorCodeType('default')
- if(code === 200){
- return Promise.resolve(res.data)
- }else{
- ElMessage.error(msg)
- return Promise.reject(res.data)
- }
- },
- error => {
- console.log('err' + error)
- hideLoading()
- let { message } = error;
- if (message == "Network Error") {
- message = "后端接口连接异样";
- }
- else if (message.includes("timeout")) {
- message = "系统接口申请超时";
- }
- else if (message.includes("Request failed with status code")) {
- message = "系统接口" + message.substr(message.length - 3) + "异样";
- }
- ElMessage.error({
- message: message,
- duration: 5 * 1000
- })
- return Promise.reject(error)
- }
- )
-
- export default service;
四、主动导入vue3相干函数(auto-imports.d.ts)
auto-imports.d.ts放在src目录下
细致:需要布置yarn add unplugin-auto-import
或者npm i unplugin-auto-import -D
布置完重启名目
代码下列:
- declare global {
- const computed: typeof import('vue')['computed']
- const createApp: typeof import('vue')['createApp']
- const customRef: typeof import('vue')['customRef']
- const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
- const defineComponent: typeof import('vue')['defineComponent']
- const effectScope: typeof import('vue')['effectScope']
- const EffectScope: typeof import('vue')['EffectScope']
- const getCurrentInstance: typeof import('vue')['getCurrentInstance']
- const getCurrentScope: typeof import('vue')['getCurrentScope']
- const h: typeof import('vue')['h']
- const inject: typeof import('vue')['inject']
- const isReadonly: typeof import('vue')['isReadonly']
- const isRef: typeof import('vue')['isRef']
- const markRaw: typeof import('vue')['markRaw']
- const nextTick: typeof import('vue')['nextTick']
- const onActivated: typeof import('vue')['onActivated']
- const onBeforeMount: typeof import('vue')['onBeforeMount']
- const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
- const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
- const onDeactivated: typeof import('vue')['onDeactivated']
- const onErrorCaptured: typeof import('vue')['onErrorCaptured']
- const onMounted: typeof import('vue')['onMounted']
- const onRenderTracked: typeof import('vue')['onRenderTracked']
- const onRenderTriggered: typeof import('vue')['onRenderTriggered']
- const onScopeDispose: typeof import('vue')['onScopeDispose']
- const onServerPrefetch: typeof import('vue')['onServerPrefetch']
- const onUnmounted: typeof import('vue')['onUnmounted']
- const onUpdated: typeof import('vue')['onUpdated']
- const provide: typeof import('vue')['provide']
- const reactive: typeof import('vue')['reactive']
- const readonly: typeof import('vue')['readonly']
- const ref: typeof import('vue')['ref']
- const resolveComponent: typeof import('vue')['resolveComponent']
- const shallowReactive: typeof import('vue')['shallowReactive']
- const shallowReadonly: typeof import('vue')['shallowReadonly']
- const shallowRef: typeof import('vue')['shallowRef']
- const toRaw: typeof import('vue')['toRaw']
- const toRef: typeof import('vue')['toRef']
- const toRefs: typeof import('vue')['toRefs']
- const triggerRef: typeof import('vue')['triggerRef']
- const unref: typeof import('vue')['unref']
- const useAttrs: typeof import('vue')['useAttrs']
- const useCssModule: typeof import('vue')['useCssModule']
- const useCssVars: typeof import('vue')['useCssVars']
- const useSlots: typeof import('vue')['useSlots']
- const watch: typeof import('vue')['watch']
- const watchEffect: typeof import('vue')['watchEffect']
- }
- export {}
五、主动导入ElementPlus相干函数(components.d.ts)
细致:需要布置npm i unplugin-vue-components -D
或者yarn add unplugin-vue-components
布置完重启名目
- import '@vue/runtime-core'
-
- declare module '@vue/runtime-core' {
- export interface GlobalComponents {
- ElCard: typeof import('element-plus/es')['ElCard']
- ElCol: typeof import('element-plus/es')['ElCol']
- ElContainer: typeof import('element-plus/es')['ElContainer']
- ElFooter: typeof import('element-plus/es')['ElFooter']
- ElHeader: typeof import('element-plus/es')['ElHeader']
- ElMain: typeof import('element-plus/es')['ElMain']
- ElOption: typeof import('element-plus/es')['ElOption']
- ElPagination: typeof import('element-plus/es')['ElPagination']
- ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
- ElRadioGroup: typeof ('element-plus/es')['ElRadioGroup']
- ElRow: typeof import('element-plus/es')['ElRow']
- ElSelect: typeof import('element-plus/es')['ElSelect']
- ElTable: typeof import('element-plus/es')['ElTable']
- ElTableColumn: typeof import('element-plus/es')['ElTableColumn']
- Loading: typeof import('element-plus/es')['ElLoadingDirective']
- }
- }
-
- export {}
六、vite.config.ts文件配置
细致:需要布置npm i unplugin-icons
或者yarn add unplugin-icons
- import { defineConfig } from 'vite';
- import vue from '@vitejs/plugin-vue';
- import Icons from "unplugin-icons/vite";
- import IconsResolver from "unplugin-icons/resolver";
- import AutoImport from "unplugin-auto-import/vite";
- import Components from "unplugin-vue-components/vite";
- import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
- import { loadEnv } from 'vite';
- import path from 'path';
- // 门路
- const pathSrc = path.resolve(__dirname,'src')
-
- // https://vitejs.dev/config/
- export default({ co妹妹and, mode }) => {
- return defineConfig({
- plugins: [
- vue(),
- AutoImport({
- // Auto import functions from Vue, e.g. ref, reactive, toRef...
- // 主动导入 Vue 相干函数,如:ref, reactive, toRef 等
- imports: ["vue"],
-
- // Auto import functions from Element Plus, e.g. ElMessage, ElMessageBox... (with style)
- // 主动导入 Element Plus 相干函数,如:ElMessage, ElMessageBox... (带样式)
- resolvers: [
- ElementPlusResolver(),
-
- // Auto import icon components
- // 主动导入图标组件
- IconsResolver({
- prefix: "Icon",
- }),
- ],
-
- dts: path.resolve(pathSrc, "auto-imports.d.ts"),
- }),
-
- // 主动导入 Element Plus 组件
- Components({
- resolvers: [
- // Auto register icon components
- // 主动注册图标组件
- IconsResolver({
- enabledCollections: ["ep"],
- }),
- // Auto register Element Plus components
-
- ElementPlusResolver(),
- ],
-
- dts: path.resolve(pathSrc, "components.d.ts"),
- }),
- // 图标
- Icons({
- autoInstall: true,
- }),
- ],
- server:{
- host: '127.0.0.1',
- //port: Number(loadEnv(mode, process.cwd()).VITE_APP_PORT),
- port: 3000,
- strictPort: true, // 端口被占用间接退出
- https: false,
- open: true,// 在开辟效劳器启动时主动在浏览器中关上应用程序
- proxy: {
- // 字符串简写写法
- '^/api': {
- target: mode==='development'?loadEnv(mode, process.cwd()).VITE_APP_DEV_URL:loadEnv(mode, process.cwd()).VITE_APP_PROD_URL,
- changeOrigin: true,
- rewrite: (path) => path.replace(/^\/api/, '')
- }
- },
- hmr:{
- overlay: false // 屏障效劳器报错
- }
- },
- resolve:{
- alias:{
- '@': pathSrc,
- }
- },
- css:{
- // css预解决器
- /*preprocessorOptions: {
- scss: {
- additionalData: '@import "@/assets/styles/global.scss";'
- }
- }*/
- preprocessorOptions: {
- less: {
- charset: false,
- additionalData: '@import "./src/assets/style/global.less";',
- },
- },
- },
- build:{
- chunkSizeWarningLimit: 1500, // 分块打包,剖析块,将年夜块剖析成更小的块
- rollupOptions: {
- output:{
- manualChunks(id) {
- if (id.includes('node_modules')) {
- return id.toString().split('node_modules/')[1].split('/')[0].toString();
- }
- }
- }
- }
- }
- })
- }
七、应用axios封装
完好的情况变量配置文件.env.production
以及.env.development
7.一、名目根目录的development文件内容下列
- # 开辟情况
- VITE_APP_TITLE = "阿绵"
- # 端口号
- VITE_APP_PORT = "3000"
- # 申请接口
- VITE_APP_DEV_URL = "http://localhost:8088"
- # 前缀
- VITE_APP_BASE_API = "/api"
7.二、名目根目录下的production文件内容下列
- # 开辟情况
- VITE_APP_TITLE = "阿绵"
- # 端口号
- VITE_APP_PORT = "3000"
- # 申请接口
- VITE_APP_DEV_URL = "http://localhost:8088"
- # 前缀
- VITE_APP_BASE_API = "/api"
八、在任何vue文件内应用接口:
细致:这里另有一个PageParams全局分页工具:
page-params.ts
代码下列:
- // 全局对于抗分页参数范例申明
- declare interface PageParams {
- pageNum: number, pageSize: number, type?: Model, // 可选参数
- readonly sort?: string // 只读可选参数
- } interface Model { type?: string }
- export default PageParams;
本文链接:https://addon.ciliseo.com/shi-zhan-jiao-cheng-vitevue30ts-zhong-ru-he-feng-zhuang-axios.html
网友评论