mock.js可以模拟实际项目中我们需要使用到的数据。mockJs

在实际项目开发中,往往后端的接口不能及时提供给我们前端,但是前端需要一些数据来查看我们布局是否合适等,所以这个时候我们就可以使用到mock,来实现 前端先行。
1.首先我们先用vue-cli创建一个我们自己项目

2.安装axios,并倒入axios

import Vue from 'vue'
import App from './App.vue'
// 引入axios
import axios from 'axios'
// 全局注册
Vue.prototype.$axios = axios
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
3.安装mockJs ,并创建一个文件夹,创建mock.js,在main.js引入文件

tip:此时我们在mock.js里面写一写,然后 npm run serve
var Mock = require('mockjs')
var data = Mock.mock({
// 属性 list 的值是一个数组,其中含有 1 到 10 个元素
'list|1-10': [{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|+1': 1
}]
})
// 输出结果
console.log(JSON.stringify(data, null, 4))
但是会报这样一个错误

我们只需要在package.json中加一句话,就不会报错了(这是因为vue不允许console.log)

4.我们跑起项目,就可以看到已经有我们想要的数据了

最后在mockJs的官网有非常全的数据的定义

可以基本上完全满足一般项目的需求~
当然,在我们前端去用mock时,我们可以和后端沟通好 我们需要的数据,以及数据结构!!!
并且,一定要在开发时及时和后端沟通,
切记❗️❗️❗️不要自己埋头苦干的开发,否者最后联调时 会十分痛苦😖
网友评论