时间:2020-10-15 23:16:11 | 栏目:JavaScript代码 | 点击:次
最近在开发项目的时候,需要用到mockjs这个包来实现前端本地数据的模拟,下面我就来说一下具体步骤:
前言
uni-app将自己的配置融合到了vue.config.js中,所以需要自己配置,需要在package.json的同级目录下新建一个vue.config.js;ajax请求的路由,因为这个路由我们希望拿到模拟数据,所以用webpack的devserve来拦截。拦截之后通过mockjs,由它来生成模拟数据,然后返回模拟值。
步骤
在vue.config.js中加入下面代码:
const Mock = require('./mock/index.js'); module.exports = { chainWebpack: (config) => { config.resolve.alias .set( '@',resolve(__dirname, '/'))//设置@为src目录的别名) }, css: { .... } }, devServer: { contentBase: path.join(__dirname, 'mock'), compress: true, port: 8080, overlay: { warnings: false, errors: true }, before(app){ Mock(app) } } };
devserver的配置中的before配置项是拦截路由请求。我们把全部交给Mock(app)处理;然后打开mock/index.js写入如下代码:
const addressesMock = require('./addresses'); const attendanceMock = require('./attendance'); const attendanceListMock = require('./attendance-list'); .... function Mock(app) { addressesMock(app) attendanceMock(app) attendanceListMock(app) ..... } module.exports = Mock;
打开addresses写入你需要mock的数据就ok啦
var Mockjs = require('mockjs') const { Random }= Mockjs; const phonePrefix = ['132', '135', '189'] const index = Math.floor(Math.random() * phonePrefix.length) var phone = phonePrefix[index] + Mockjs.mock(/\d{8}/) const addressesMock = function (app) { app.get('/api3/addresses', function(req, res) { var data = Mockjs.mock({ // 属性 list 的值是一个数组,其中元素的数量从 1 到 10 个都有可能,随机 'list|1-10': [{ 'id|+1': 0, "accept_name": Random.cname(), "mobile": phone, "province_name": Random.province(), "area": Mockjs.mock(/\d{6}/), "city": Mockjs.mock(/\d{6}/), "sex": parseInt(Random.boolean()), "district": { "districts": Random.province()+Random.city()+Random.county(), "area": Random.county(), "city": Random.city(), "province": Random.province() }, "street": "有一间公寓八栋", "inner": false, "lat": "", "door_number": "AB1234", "is_default": parseInt(Random.boolean()), "province": Mockjs.mock(/\d{6}/), "area_name":Random.county(), "city_name": Random.city(), "poiname": "" }] }) res.json(data); }) } module.exports = addressesMock;
在需要接口的地方之间用 就能得到相应数据了
this.$ajax.get('/api3/addresses').then(res => { // 调用接口 })