一、什么是mock.js?
生成随机数据,拦截 Ajax 请求。
通过随机数据,模拟各种场景;不需要修改既有代码,就可以拦截 Ajax 请求,返回模拟的响应数据;支持生成随机的文本、数字、布尔值、日期、邮箱、链接、图片、颜色等;支持支持扩展更多数据类型,支持自定义函数和正则。
二、为什么使用mock.js
在做开发时,当后端的接口还未完成,前端为了不影响工作效率,手动模拟后端接口,
我们可以使用json文件来模拟后台数据,但比较局限,无法模拟数据的增删改查
使用json-server模拟,但不能随机生成所需数据
使用mockjs模拟后端接口,可随机生成所需数据,可模拟对数据的增删改查
{
// `data` 由服务器提供的响应
data: {},
// `status` HTTP 状态码
status: 200,
// `statusText` 来自服务器响应的 HTTP 状态信息
statusText: "OK",
// `headers` 服务器响应的头
headers: {},
// `config` 是为请求提供的配置信息
config: {}
}
<body>
<div id="app">
<h1>网站列表</h1>
<div
v-for="site in info"
>
{{ site.name }}
</div>
</div>
<script type = "text/javascript">
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('https://www.runoob.com/try/ajax/json_demo.json')
.then(response => (this.info = response.data.sites))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
})
</script>
</body>
</html>
{
"data": {
"name": "网站",
"num": 3,
"sites": [
{
"name": "Google",
"info": [
"Android",
"Google 搜索",
"Google 翻译"
]
},
{
"name": "Runoob",
"info": [
"菜鸟教程",
"菜鸟工具",
"菜鸟微信"
]
},
{
"name": "Taobao",
"info": [
"淘宝",
"网购"
]
}
]
},
"status": 200,
"statusText": "",
"headers": {
"accept-ranges": "bytes",
"age": "96850",
"ali-swift-global-savetime": "1585128839",
"cache-control": "s-maxage=163749, max-age=163749",
"content-length": "291",
"content-type": "application/json",
"date": "Tue, 23 Jun 2020 03:51:34 GMT",
"eagleid": "793f8d1e15929811442472602e",
"etag": "\"5ce7cb1c-123\"",
"expires": "Thu, 25 Jun 2020 01:20:43 GMT",
"last-modified": "Fri, 24 May 2019 10:44:44 GMT",
"server": "Tengine",
"status": "304",
"timing-allow-origin": "*",
"via": "cache37.l2cn1837[0,304-0,H], cache68.l2cn1837[0,0], cache2.cn284[0,304-0,H], cache10.cn284[0,0]",
"x-cache": "HIT TCP_IMS_HIT dirn:13:391583864",
"x-swift-cachetime": "86400",
"x-swift-savetime": "Wed, 24 Jun 2020 01:20:43 GMT"
},
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*"
},
"method": "get",
"url": "https://www.runoob.com/try/ajax/json_demo.json"
},
"request": {}
}
- 不需要修改既有代码,就可以拦截 Ajax 请求,
模拟返回的响应数据
; - 数据类型丰富;
- 通过随机数据,模拟各种场景;
npm install mockjs --save-dev
入口js(main.js)里引入mockjs
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
//1.引入组件 import Vue from 'vue'
//2. 引入app.vue用它的内容来替换div id = app import App from './App'
//3. 构建vue实例
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
// 引入mockjs
require('./mock.js')
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: {
App
}
})
Vue.filter('getYMD', function(input) {
return input.split(' ')[0];
})
// 引入mockjs
const Mock = require('mockjs');
// 获取 mock.Random 对象
const Random = Mock.Random;
// mock一组数据
const produceNewsData = function() {
let articles = [];
for (let i = 0; i < 100; 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 {
articles: articles
}
}
// Mock.mock( url, post/get , 返回的数据);
Mock.mock('/news/index', 'post', produceNewsData);
hello.vue
<template>
<div class="index">
<div v-for="(item, key) in newsListShow">
<news-cell
:newsDate="item"
:key="key"
></news-cell>
</div>
</div>
</template>
<script>
import api from './../axios/api.js'
import NewsCell from './NewsCell.vue'
export default {
name: 'index',
data() {
return {
newsListShow: [],
}
},
components: {
NewsCell
},
created() {
this.setNewsApi();
},
methods: {
setNewsApi: function () {
api.JH_news('/news/index', 'type=top&key=123456')
.then(res => {
console.log(res);
this.newsListShow = res.articles;
});
},
}
}
</script>
import axios from 'axios'
import vue from 'vue'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 请求拦截器
axios.interceptors.request.use(function(config) {
return config;
}, function(error) {
return Promise.reject(error);
})
// 响应拦截器
axios.interceptors.response.use(function(response) {
return response;
}, function(error) {
return Promise.reject(error);
})
// 封装axios的post请求
export function fetch(url, params) {
return new Promise((resolve, reject) => {
axios.post(url, params)
.then(response => {
resolve(response.data);
})
.catch((error) => {
reject(error);
})
})
}
export default {
JH_news(url, params) {
return fetch(url, params);
}
}
NewsCell.vue
<template>
<section class="financial-list">
<section class="collect" @click="jumpPage">
<aside>
<h2>{{newsDate.title}}</h2>
<section class="Cleft clearfix">
<img class="fl" src="./../assets/icon/eyes.png" style="width:0.24rem;height:0.2rem;">
<span class="fl">{{newsDate.author_name}}</span>
</section>
<section class="Cright">
<img src="./../assets/icon/clock.png" style="width:0.2rem;height:0.2rem;">
<span>{{newsDate.date | getYMD}}</span>
</section>
<div style="clear: both"></div>
</aside>
<aside>
<img :src="newsDate.thumbnail_pic_s" style="border-radius: 0.2rem;">
</aside>
<div style="clear: both"></div>
</section>
</section>
</template>
<script>
export default {
name: 'NewsCell',
props: {
newsDate: Object
},
data () {
return {
}
},
computed: {
},
methods: {
jumpPage: function () {
window.location.href = this.newsDate.url
}
}
}
</script>
路由
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello
}
]
})