7
在vite2和Vue3中配置Mockjs
source link: http://www.fly63.com/article/detial/10527
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
时间: 2021-07-12阅读: 45标签: vite分享
扫一扫分享
在 Vite2 与 vue3 中使用Mockjs时有一些官方文档没有提到的注意点,特意做此记录。
1. Mockjs 依赖的安装
# 使用 npm 安装
npm install mockjs vite-plugin-mock cross-env -D
# 使用 yarn 安装
yarn add mockjs vite-plugin-mock cross-env -D
2. 在 package.json 中设置环境变量
{
"scripts": {
// 修改dev构建脚本的命令
"dev": "cross-env NODE_ENV=development vite",
"build": "vite build",
"serve": "vite preview"
}
}
3. 在 vite.config.js 中添加 mockjs 插件
import vue from "@vitejs/plugin-vue";
import { viteMockServe } from "vite-plugin-mock";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [
vue(),
viteMockServe({
supportTs: false
})
],
});
4. 在项目中创建 mock 文件夹,在其中创建需要的数据接口
// 仅做示例: 通过GET请求返回一个名字数组
export default [
{
url: "/api/getUsers",
method: "get",
response: () => {
return {
code: 0,
message: "ok",
data: ["tom", "jerry"],
};
},
},
];
5. 在项目中使用此接口
fetch("/api/getUsers")
.then(response => {
response.json()
})
.then(data => {
console.log(data)
})
会得到如下返回值:
{
code: 0,
data: {
0: "tom",
1: "jerry",
},
length: 2,
message: "ok"
}
至此,我们就完成了mockjs的配置。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK