vue3+vite+axios+ElementPlus+ElLoading简易封装

时间:2024-05-07 10:32:26

1.安装按需加载element-plus需要的依赖包

pnpm install element-plus
pnpm install axios
# 按需自动导入
pnpm install -D unplugin-vue-components unplugin-auto-import
# 自动导入element-plus样式
pnpm install -D vite-plugin-style-import

2.修改jsconfig.json

{
  "compilerOptions": {
    "paths": {
      "@/*": ["./src/*"]
    },
    "types": ["element-plus/global"] // 增加element-plus组件标签代码提示
  },
  "exclude": ["node_modules", "dist"]
}

3.修改vite.config.js

import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import {
  createStyleImportPlugin,
  ElementPlusResolve,
} from "vite-plugin-style-import";

export default defineConfig({
  plugins: [
    vue(), // element-plus组件自动引入
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
    // element-plus反馈组件样式自动引入
    createStyleImportPlugin({
      resolves: [ElementPlusResolve()],
      libs: [
        {
          libraryName: "element-plus",
          esModule: true,
          resolveStyle: (name) => {
            return `element-plus/theme-chalk/${name}.css`;
          },
        },
      ],
    }),
  ],
  // 加了这个配置后, 可以在任意组件中访问到scss全局变量
  css: {
    preprocessorOptions: {
      scss: {
        javascriptEnabled: true,
        additionalData: '@import "./src/assets/css/variable.scss";',
      },
    },
  },

  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
});

4.axios二次封装

// /src/utils/request.js  - 对axios的简易封装
import axios from "axios";
import { ElLoading } from "element-plus";
import { getItem } from "@/utils/storage";
// 默认loading为false
const DEFAULT_LOADING = false;

// 保证当一个页面中有多个请求时, loading只显示一次
let loadingCount = 0;
let loadingInstrance = null;

function startLoading() {
  if (loadingCount === 0) {
    loadingInstrance = ElLoading.service({
      lock: true,
      text: "正在加载...",
      background: "rgba(0, 0, 0, 0.5)",
    });
  }
  loadingCount++;
}

function endLoading() {
  if (loadingCount > 0) {
    loadingCount--;
    if (loadingCount === 0) {
      loadingInstrance.close();
    }
  }
}

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 10000,
});

request.interceptors.request.use(
  (config) => {
    const token = getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    config.showLoading = config.showLoading ?? DEFAULT_LOADING;

    config.showLoading && startLoading();

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  (res) => {
    res.config.showLoading && endLoading();
    return res.data;
  },
  (error) => {
    error.config.showLoading && endLoading();
    return Promise.reject(error);
  }
);

export default request;

5.api的封装

// src/apis/index.js
import request from "@/utils/request";

export function getMessage() {
  return request({
    url: "https://api.uomg.com/api/rand.qinghua",
    showLoading: true, // showLoading为true时, 该接口就会出现加载中动画
  });
}

6.api的使用

<!-- App.vue -->
<template>
  <h2>{{ message }}</h2>
  <el-button @click="handleGetMessage"> 获取消息 </el-button>
</template>

<script setup>
import { ref } from "vue";
import { getMessage } from "@/apis";
const message = ref("");
const handleGetMessage = async () => {
  const res = await getMessage();
  message.value = res.content;
};
handleGetMessage();
</script>

在这里插入图片描述
在这里插入图片描述