之前用EASY-MOCK来模拟接口,但是这网站三天两头GG,太生气了~!
发现可以自己在项目里使用Mock,开始使用~
安装VUE在这里不写了,先从安装Mock开始:
安装mockjs
npm install mockjs --save-dev
新建mock目录,创建login.js
import Mock from 'mockjs';
// 获取 mock.Random 对象
const Random = Mock.Random;
const loginData = function (opt) {
const { user } = JSON.parse(opt.body)
return {
result: 200,
data: {
uid:Random.id(),
type: 1,
uname:user,
expire_in: "63666",
token: Random.guid(),
logintime: Random.now()
}
}
}
export default {
login: opt => loginData(opt)
};
该方法返回的是一个随机生成ID的数据
接着在mock目录下新建index.js
import Mock from 'mockjs';
import loginAPI from './login';
Mock.mock(/\/login/, 'post', loginAPI.login);
最后在VUE的主工程main.js里引入mock
import Vue from 'vue'
import App from '@/App'
import router from '@/router'
import store from '@/store/'
//解决低版本兼容问题
import "babel-polyfill";
// 引入mockjs
require('./mock/index.js')
Vue.config.productionTip = false
Vue.use(ElementUI);
Vue.prototype.$get = get;
Vue.prototype.$post = post;
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
Mock使用的方法有很多,比如分页时返回一个列表,或者直接返回一个结果
import Mock from 'mockjs'
import { param2Obj } from '@/utils'
// 获取 mock.Random 对象
const Random = Mock.Random;
const userData = function (opt) {
const { page, pageSize } = param2Obj(opt.url)
let len = (1000 - pageSize * (page - 1)) < pageSize ? (1000 - pageSize * (page - 1)) : pageSize;
let _data = []
let i = 0;
for (i; i < len; i++) {
_data.push(
Mock.mock({
"id": "@id",
"dateTime": "@now()",
"name": "@name()",
"address": "上海市普陀区金沙江路 1518 弄",
"state": "@integer(0, 1)"
})
);
}
return _data;
}
export default {
getUserList: opt => {
return {
result: 200,
data: {
data: userData(opt),
count:1000
}
}
},
addUser: () => {
return {
"result": 200,
"data": {},
"msg": "请求成功"
}
}
}
这些方法够用了,mock还有一些可以随机生成时间、id、uid的方法,到时候用到再查吧~