Mock.js生成随机数据,拦截 Ajax 请求
参考文档:https://github.com/nuysoft/Mock/wiki/Getting-Started
语法规范:https://github.com/nuysoft/Mock/wiki/Syntax-Specification
一、Node.js
安装
npm install mockjs
示例
// 使用 Mock var Mock = require('mockjs') /** * * 数据模板 * 属性名|生成规则: 属性值 */ var data = Mock.mock({ // 属性 list 的值是一个数组,其中含有 1 到 10 个元素 'list|1-10': [{ // 属性 id 是一个自增数,起始值为 1,每次增 1 'id|+1': 1, 'name': '@FIRST' }] }) // 输出结果 console.log(JSON.stringify(data, null, 4))
运行结果
{ "list": [ { "id": 1, "name": "Larry" }, { "id": 2, "name": "Edward" }, { "id": 3, "name": "Jessica" }, { "id": 4, "name": "William" }, { "id": 5, "name": "Christopher" }, { "id": 6, "name": "Michael" }, { "id": 7, "name": "Susan" }, { "id": 8, "name": "Shirley" }, { "id": 9, "name": "Angela" }, { "id": 10, "name": "George" } ] }
二、浏览器中
使用示例
<script src="https://cdn.bootcdn.net/ajax/libs/Mock.js/1.0.1-beta3/mock-min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script> <div id="app"> <span>{{info.name}}</span> <span>{{info.age}}</span> <span>{{info.date}}</span> </div> <script> // 生成数据 Mock.mock("http://mockjs", { name: "@cname", //模拟名称 "age|1-100": 100, //模拟年龄(1-100) date: "@date('yyyy-MM-dd')", //模拟时间 }); const app = new Vue({ el: "#app", data: () => { return { info: {}, }; }, // http请求拦截 methods: { async getData() { const res = await axios.get("http://mockjs"); this.info = res.data; }, }, created() { this.getData(); }, }); </script>
更多示例:http://mockjs.com/examples.html
参考