mockjs
mockjs解决后端请求没有完成时 前端的数据编写和请求拦截
mockjs安装
vue项目中通过npm i mockjs -D 安装 通过import 引入mockjs\
import Mock from 'mockjs'
数据编写
规则
属性值 规则 属性值所组成
'name|1:string 表示的是name属性重复的次数为1次 规则可以省略
- 规则有7种目前我常用的有一下几种
‘name|min-max’:value 属性值 随机的在min-max中重复的次数
‘name|count’;value 属性值重复count次
‘name|+step’:value 属性值每次增加step
规则值的属性参考:
https://www.kancloud.cn/sophie_u/mockjs/532227
模板占位符
占位符采用两种方式一种是Random,xxxx(),另一种方式是 Mock.mock(’@xxxx’)使用占位符
Random方法 常用
1.Random.ingeger(min,max) //生成minx-max之间的随机数 min,max可以不传
2.Random.date(format)随机日期 format是日期 格式可以不传
3.Random.image(size,backgrond,color,text)图片
4 Random.paragraph( min?, max? ) 段落
5. Random.title( min?, max? )
6. Random.cparagraph( min?, max? ) 中文段落
7. Random.csentence( min?, max? ) 中文句子
8. Random.cword( pool?, min?, max? ) 汉字
9. Random.ctitle( min?, max? ) 标题
10… Random.cname() 中文姓名
10. Random.url() 随机URL
11. Random.increment( step? ) 递增
12. Random.city(true) 省 市
//生成人员的数据
const {personData}=Mock.mock({
'personData|7-39':[
{
name:"@cname()",
age:"@character(number)",
image:"@image('100*100','red','white','凯强')",
city:"@city(true)",
'list|2-8':[{
names:"@cname()",
title:"@ctitle()",
id:"@increment()",
date:"@date(yyyy-MM-dd hh:mm:ss)"
}]
}
]
})
请求拦截
get拦截 一般采用的是通过正则表达式进行路径的匹配
//mock进行数据的拦截
Mock.mock(/\/api\/get/,'get',(options)=>{
//options是请求的数据参数 url是请求的url get请求的参数拼接在url上,post请求的参数则在option的body中 通过JSON.parse()格式化传递过来的数据
// console.log('get',options)
let currentPage=options.url.split('?')[1].split('&')[0].split('=')[1];
let pageSize=options.url.split('?')[1].split('&')[1].split('=')[1];
console.log(personData)
return {
satatus:200,
data: personData.slice((currentPage-1)*pageSize,currentPage*pageSize),
total:personData.length
}
})
post拦截
const {personData}=Mock.mock({//人员数据的生成
'personData|7-39':[
{
name:"@cname()",
age:"@character(number)",
image:"@image('100*100','red','white','凯强')",
city:"@city(true)",
'list|2-8':[{
names:"@cname()",
title:"@ctitle()",
id:"@increment()",
date:"@date(yyyy-MM-dd hh:mm:ss)"
}]
}
]
})
//post请求
Mock.mock('/api/post','post',(option)=>{
let {data}=JSON.parse(option.body)
console.log('aa',data)
personData.push({//通过push的方式可以实现数据的新增
name:data.name,
age:data.age,
image:"@image('100*100','red','white','凯强')",
city:"@city(true)",
})
return {
satatus:200,
total:personData.length
}
})
后续持续更新