1.安装按需加载element-plus需要的依赖包
pnpm install element-plus
pnpm install axios
pnpm install -D unplugin-vue-components unplugin-auto-import
pnpm install -D vite-plugin-style-import
2.修改jsconfig.json
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
},
"types": ["element-plus/global"]
},
"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(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
createStyleImportPlugin({
resolves: [ElementPlusResolve()],
libs: [
{
libraryName: "element-plus",
esModule: true,
resolveStyle: (name) => {
return `element-plus/theme-chalk/${name}.css`;
},
},
],
}),
],
css: {
preprocessorOptions: {
scss: {
javascriptEnabled: true,
additionalData: '@import "./src/assets/css/variable.scss";',
},
},
},
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
});
4.axios二次封装
import axios from "axios";
import { ElLoading } from "element-plus";
import { getItem } from "@/utils/storage";
const DEFAULT_LOADING = false;
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的封装
import request from "@/utils/request";
export function getMessage() {
return request({
url: "https://api.uomg.com/api/rand.qinghua",
showLoading: true,
});
}
6.api的使用
<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>