一般项目做法:
<html>
<head>
<script src="http://requirejs.org/docs/release/2.1.16/comments/require.js"></script>
</head>
</html>
<script>
// 配置 Mock 路径
require.config({
paths: {
mock: 'http://mockjs.com/dist/mock' } }) // 加载 Mock,可以吧这里另外存为一个文件如mock.js require(['mock'], function(Mock) { // Mock.mock(rurl, template) Mock.mock('hello.json', { 'list|1-10': [{ 'id|+1': 1, 'email': '@EMAIL', 'regexp3': /\d{5,10}/ }] })
//需要mock.js的地方处理数据 $.ajax({ url: 'hello.json', dataType: 'json' }).done(function(data, status, jqXHR) { $('<pre>').text(JSON.stringify(data, null, 4)) .appendTo('body') }) })
</script>
vue-cli项目
//首先的install mockjs
//main.js中,引入mockjs require('./mock') //mock.js中,引入mockjs const Mock = require('mockjs')
//组建中使用mock.js
import 'mock.js' //注意路径
示例:
mock.js
const produceData = function(opt) {
console.log('opt', opt);
let articles = [];
for (let i = 0; i < 30; i++) {
let newArticleObject = {
title: Random.csentence(5, 30), // Random.csentence( min, max )
thumbnail_pic_s: Random.dataImage('300x250', 'mock的图片'), // Random.dataImage( size, text ) 生成一段随机的 Base64 图片编码
author_name: Random.cname(), // Random.cname() 随机生成一个常见的中文姓名
date: Random.date() + ' ' + Random.time() // Random.date()指示生成的日期字符串的格式,默认为yyyy-MM-dd;Random.time() 返回一个随机的时间字符串
}
articles.push(newArticleObject)
}
return {
data: articles
}
}
Mock.mock('http://localhost:8013/news', /post|get/i, produceData);
export default {
produceData
};
//vue组建中处理数据
mounted() {
this.$http.post('http://localhost:8013/news')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
}