最近没那么忙了,就想着自己写一个后台管理系统的小demo。刚好最近把Vue3的文档撸了一遍,正好可以顺便练习一下Vue3+ts。
1、mockjs是必不可少的。
2、vite-plugin-mock。由于现在创建Vue3项目默认都使用vite,而不再是webpack(没有说webpack不好的意思),在vite中使用mockjs的话,是需要借助 这个插件
3、axios(用原生的也行,注意跨越问题)
npm install mockjs vite-plugin-mock axios
or
yarn add mockjs vite-plugin-mock axios
// vite.config.ts
import { fileURLToPath, URL } from "node:url";
import type { UserConfigExport, ConfigEnv } from "vite";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { viteMockServe } from "vite-plugin-mock"; // 从插件中导入viteMockServe
export default defineConfig({
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
viteMockServe(), // 跟vue一样被当作函数执行,里面有一些参数可配置。这里不具体展开介绍。感兴趣的小伙伴自己去查阅资料哈
],
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
},
css: {
preprocessorOptions: {
less: {
modifyVars: {
hack: `true; @import (reference) "${resolve(
"src/assets/css/global.less"
)}";`,
},
javascriptEnabled: true,
},
},
},
});
在项目根目录下创建一个名为mock的文件夹,在文件夹下面创建index.ts文件
// mock/index.ts
import type { MockMethod } from "vite-plugin-mock"; // !!!看这里,这个MockMethod 是个类型,不是方法,导入的时候要type。要么就直接不导入,直接在文件中到处一个数组即可
const arr: any = [];
for (let index = 0; index < 20; index++) {
arr.push({
customer_name: "wade",
status_text: "登录成功",
os: "Windows 10",
browser: "Chrome(99.0.4844.51)",
ip: "192.168.9.110",
created: "2021-12-14 10:41:02",
location: "局域网 局域网",
});
}
const logList = {
total: 31,
page: 1,
page_size: 20,
list: arr,
};
const statusList = {
data: [
{ label: "全部", value: 0 },
{ label: "待审核", value: 1 },
],
};
export default [
{
url: "/api/getList",
method: "post",
response: () => {
return logList;
},
},
{
url: "/api/getStatusList",
method: "get",
response: () => {
return statusList;
},
},
] as MockMethod[];
<template>
<div class="home-page">
<h1>我是首页</h1>
<button @click="aa">按钮</button>
</div>
</template>
<script lang="ts" setup>
import axios from "axios";
function aa() {
// 调用的时候如果报错404,请认真检查一下自己的url是否存在(我就是粗心写错了,还在网上查了半天,尴尬)
axios.get("/api/getStatusList").then((res) => {
console.log("login", res);
});
}
</script>
<style scoped lang="less">
.home-page {
width: 1200px;
background-color: pink;
}
</style>
大概长这样,加了之后就能顺利运行啦!当然,也可以不使用 MockMethod 直接导出一个数组即可
// mock/index.ts
export default [
{
type: "get",
url: "/user/login",
response: () => {
return { isAuth: true };
},
},
];