mock数据-vite-plugin-mock和moxkjs
一、安装mockjs(http://mockjs.com/)
yarn add mockjs -S 或 npm i mockjs -D
二、安装vite-plugin-mock
npm i vite-plugin-mock -D
三、在src目录下创建mock文件夹,在文件夹内创建js文件(注:URL要和真实请求地址保持一致)
例如: 定义mock.js 新建mock文件夹 mock.js
在main.js导入:
import '@/mock/mock.js'
在mock.js中导入Mock
import Mock from 'mockjs';
import { MockMethod } from "vite-plugin-mock";
export default [
{
url: "/mock-login", // 注意,这里只能是string格式
method: "post",
response: () => {
return {
menusList: [1,2,3,4,],
};
},
},
] as MockMethod[]
四, Mock的三种写法:
Mock(url,method,data)
//mock.js
Mock.mock("/api/getData", "get", function(options) {
return {
"name": "mewow",
"age": 18
}
})
//MockView.vue
request.get("/api/getData").then(res => {
console.log("mock", res.data);
})
Mock(url,data)
//mock.js
Mock.mock("/api/getData2", {
"name": "mewow",
"age": 18
})
//MockView.vue
request.get("/api/getData2").then(res => {
console.log("mock2", res.data);
})
Mock(url,method,function(options){
return {data数据}
})
mock.js中的url接收正则写法,再截取url,利用qs.js可将字符串转为对象,获取url中的属性
//mock.js
Mock.mock(/\/api\/getData3/, "get", function(options) {
var str = options.url.slice(options.url.indexOf("?") + 1);
var elem = qs.parse(str)
return {
"name": elem.name,
"age": elem.age
};
})
//MockView.vue
request.get("/api/getData3?name=mewow&age=18").then(res => {
console.log("mock3", res.data);
})
三种写法的运行结果:
五、在vite.config.ts进行个人配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { viteMockServe } from 'vite-plugin-mock'
import path from "path"
export default defineConfig({
plugins:[
vue(),
viteMockServe({
mockPath: "./src/mock/", // 指向mock下的文件
localEnabled: true // 是否开启开发环境
}
],
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
},
})
配置路径别名时需要在tsconfig.json文件下配置
{
"paths": {
"@/*": ["src/*"]
}
}
(注)mock.js常用数据模板
//mock.js
import Mock from 'mockjs';
import qs from "qs"
Mock.mock(/\/api\/random/, function(options) {
var str = options.url.slice(options.url.indexOf("?") + 1);
var elem = qs.parse(str)
return Mock.mock({
status: 0,
"ename": elem.name,
"list|10": [{
"id|+1": 1234,//id 从1234累加
"name": "@cname",//随机中文姓名
"age|1-200": 1,//1-200间的随机整数
"price|200-500.2-5": 1,//200-500间 随机2-5位小数
"star|1-5": "★",//随机1-5个★
"chart|2": "hello",//字符串重复两次
"love|1": true,//随机布尔值
"arr|1": ["a", "b", "c", "d"],//随机数组中的一项
"obj": {
"h|150-165": 1,
"weight|85-120": 1,
"money|1000-9999": 1
},
"aprice": function() {//随机数值拼接
return this.price + this.name
},
"tel": /1\d{10}/,//可接收正则
"pic": function() {//随机演示图片
return Mock.Random.dataImage('200x100', this.name)
},
"date": "@date(yyyy/MM/dd)",//随机日期
"time": "@time", //Mock.Random.time()//随机时间
"pdate": "@datetime()",//随机日期和时间
"now": "@now()",//当前日期和时间
"das": "@cparagraph(1, 3)",//随机一段话
"keyword": "@cword(3, 5)",//随机2-5个子
"email": /[\w\d]{8,12}\@(126|163|qq)\.(com|cn|org)/,//正则 邮箱格式
"ip": "@ip()",//随机ip
"address": "@county(true)"//随机省市区
}]
})
})