一、安装
简单粗暴
npm install mockjs
二、引入
CommonJS引入
let Mock = require('mockjs')
let userInfo = Mock.mock({data: {responseCode: 200,responseMessage: 'success',userMessage: {name: "@cname",email: "@email",msg: '@cparagraph(2)'}}
})
或者ES6的引入方式
import Mock from 'mockjs'
三、使用
3.1 单独写一个mockData.js文件
mockData.js
let Mock = require('mockjs')
let userInfo = Mock.mock({data: {responseCode: 200,responseMessage: 'success',userMessage: {name: "@cname",email: "@email",msg: '@cparagraph(2)'}}
})let mockData = {userInfo: userInfo
}export default mockData
在页面中import数据使用
3.2 使用vuex去控制是否使用mockData.js的数据
store.js
import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex);const state = {//使用模拟数据, 只是开发时使用, 如果不是开发时, 请务必设置为falseuseMock: true
}export default new Vuex.Store({state
})
在HelloWorld.vue
里
created() {if (this.$store.state.useMock) {//使用延时器模拟异步window.setTimeout(() => {let arr = [];arr.push(mockData.userInfo.data.userMessage);this.tableData = arrconsole.log(mockData);//业务逻辑}, 1000);return;}// 若不使用刚刚mockData.js中的数据,走下面这个方式,发起请求axios.get("http://localhost:8090/test.action").then((res) => {console.log(res)this.tableData = res.data.userInfo}).catch(function(error) {console.log(error)})},
3.3 express+mockjs写一个后台
前端的代码进入联调阶段只需要修改一个basePath,所有的接口名字都可以和约定好的路径保持一致,可以测试post请求,模拟网络环境
先装expressnpm install express
MockServer.js
let express = require('express'); //引入express
let Mock = require('mockjs'); //引入mocklet app = express(); //实例化express/*为app添加中间件处理跨域请求*/
app.use(function(req, res, next) {res.header("Access-Control-Allow-Origin", "*");res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');res.header("Access-Control-Allow-Headers", "X-Requested-With");res.header('Access-Control-Allow-Headers', 'Content-Type');next();
});app.all('/test.action', function(req, res) { //指定路径res.json(Mock.mock({"status": 200,"userInfo|10": [{name: "@cname",email: "@email",msg: '@cparagraph(2)'}]}));
});app.listen('8090', () => {console.log('监听端口 8090')
})
package.json
"scripts": {"serve": "vue-cli-service serve","build": "vue-cli-service build","lint": "vue-cli-service lint","mock": "node ./src/components/MockServer" 这里路径要写对},
这样就可以在根目录下使用npm run mock
来启动后台了,在http://localhost:8090/test.action看到模拟的数据
前端页面显示