在先后端分离开发过程当中,后端接口没有开发完成以前,前端能够用已有的接口文档,在真实的请求上拦截ajax,并根据mockjs的mock数据的规则,模拟真实接口返回的数据,并将随机的模拟数据返回参与相应的数据交互处理,这样真正实现了先后台的分离开发。javascript
与以往的本身模拟的假数据不一样,mockjs能够带给咱们的是:在后台接口未开发完成以前模拟数据,并返回,完成前台的交互;在后台数据完成以后,你所作的只是去掉mockjs:中止拦截真实的ajax,仅此而已。css
npm install mockjs --save-dev
// 引入mockjs const Mock = require('mockjs'); // 获取 mock.Random 对象 const Random = Mock.Random; // mock一组数据 const produceNotifysData= function () { let articles = []; for (let i = 0; i < 5; i++) { let newArticleObject = { title: Random.csentence(5, 30), // Random.csentence( min, max ) notifyPic: Random.dataImage('300x250', 'mock的图片'), // Random.dataImage( size, text ) 生成一段随机的 Base64 图片编码 notifyType: Random.integer(1, 3), //随机生成1-3的Integer isTop: Random.integer(1, 2), //随机生成1-2的Integer createUser: Random.cname(), // Random.cname() 随机生成一个常见的中文姓名 createTime: Random.date() + ' ' + Random.time() // Random.date()指示生成的日期字符串的格式,默认为yyyy-MM-dd;Random.time() 返回一个随机的时间字符串 } articles.push(newArticleObject) } return { articles: articles } } // Mock.mock( url, post/get , 返回的数据); Mock.mock('/admin/notify', 'get', produceNotifysData);
Mock.mock( rurl, rtype, template ),其中 rurl 的定义是前端
rurl可选。能够为正则
表示须要拦截的 URL,能够是 URL 字符串或 URL 正则。例如
/\/domain\/list\.json/、’/domian/list.json’。vue
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import iView from 'iview'; import 'iview/dist/styles/iview.css'; Vue.use(iView); Vue.config.productionTip = false // 引入mockjs require('./mock.js') /* eslint-disable no-new */ new Vue({ el: '#app', router, components: {App}, template: '<App/>' })
mounted() { //获取公告列表 this.getAdminNotifyList(); }, methods: { getAdminNotifyList() { this.$axios.get('/admin/notify').then(resp => { this.notifyList = resp.data.articles; //打印返回数据 console.log(this.notifyList) }).catch(err => { console.log(err) }) } }