前端Json数据模拟神器mockJs使用教程

一般项目做法:

 
 

<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项目

//首先main.js中,引入mockjs
require('./mock')

//mock.js中,引入mockjs
const Mock = require('mockjs')
//使用mockjs模拟数据
Mock.mock('/api/data', (req, res) => {
    return {
        data: ['a','b']
    }
})

猜你喜欢

转载自www.cnblogs.com/lwj820876312/p/9085502.html
今日推荐