vue+mockjs 模拟数据,实现前后端分离开发
在项目中尝试了mockjs,mock数据,实现前后端分离开发。
关于mockjs,官网描述的是
1.前后端分离
2.不需要修改既有代码,就可以拦截 Ajax 请求,返回模拟的响应数据。
3.数据类型丰富
4.通过随机数据,模拟各种场景。
等等优点。
总结起来就是在后端接口没有开发完成之前,前端可以用已有的接口文档,在真实的请求上拦截ajax,并根据mockjs的mock数据的规则,模拟真实接口返回的数据,并将随机的模拟数据返回参与相应的数据交互处理,这样真正实现了前后台的分离开发。
与以往的自己模拟的假数据不同,mockjs可以带给我们的是:在后台接口未开发完成之前模拟数据,并返回,完成前台的交互;在后台数据完成之后,你所做的只是去掉mockjs:停止拦截真实的ajax,仅此而已。
下面一步步的来实现vue-cli创建项目并添加一条新闻类的数据模拟接口:
1.安装vue-cli全局脚手架
npm install --global vue-cli
2.创建vue项目
vue init webpack mockjs
cd mockjs
npm install axios --save
3.安装mockjs
npm install mockjs --save-dev
4.项目目录

axios/api 用来封装axios
Hello.vue 页面首页
NeswCell.vue 新闻组件
router/index.js 路由
main.js 入口js
mock.js mockjs文件
在来看下完成后的效果

5.在入口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.
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];
})
这里我添加了额一个常用的时间整理过滤器 getYMD
6. 添加一个mock规则(mock.js)
// 引入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);
7.在Hello.vue 中请求文档接口,并接收mock数据
<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> <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.topNav{
width: 100%;
background: #ED4040;
position: fixed;
top:0rem;
left: 0;
z-index: 10;
}
.simpleNav{
width: 100%;
line-height: 1rem;
overflow: hidden;
overflow-x: auto;
text-align: center;
font-size: 0;
font-family: '微软雅黑';
white-space: nowrap;
}
.simpleNav::-webkit-scrollbar{height:0px}
.simpleNavBar{
display: inline-block;
width: 1.2rem;
color:#fff;
font-size:0.3rem;
}
.navActive{
color: #000;
border-bottom: 0.05rem solid #000;
}
.placeholder{
width:100%;
height: 1rem;
}
</style>
注意:api.JH_news是我封装的axios函数
axios/api.js如下
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);
}
}
8.在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> <style scoped>
.financial-list {
width: 100%;
height: 100%;
background-color: white;
padding: 0.28rem 0;
border-bottom: 1px solid #ccc;
} .financial-list .collect {
width: 92%;
margin: 0 auto;
} .financial-list .collect aside:nth-of-type(1) {
width: 63%;
float: left;
} .financial-list .collect aside:nth-of-type(2) {
width: 32%;
height: 2rem;
float: left;
margin-left: 0.3rem;
} .financial-list .collect h2 {
width: 100%;
height: 0.96rem;
font-size: 0.32rem;
color: #333333;
line-height: 0.48rem;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
overflow: hidden;
} .financial-list .collect aside:nth-of-type(2) img {
width: 100%;
height: 100%;
} .financial-list .collect aside .Cleft {
width: 45%;
float: left;
margin-top: 0.66rem;
} .financial-list .collect aside .Cleft span{
display: block;
width: 1.4rem;
margin-left: 0.05rem;
white-space: nowrap;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
overflow: hidden;
} .financial-list .collect aside .Cright {
width: 55%;
float: right;
margin-top: 0.66rem;
}
.financial-list .collect aside .Cright span{
display: inline-block;
margin: 0.04rem 0 0 0.05rem;
}
.financial-list .collect aside span {
font-size: 0.2rem;
color: #999999;
} .financial-list .collect aside .Cleft img,
.financial-list .collect aside .Cright img {
width: 0.18rem;
height: 0.24rem;
margin-top: 0.09rem;
}
</style>
完成
9.所有代码可以查看我的github: https://github.com/Jasonwang911/vue_mockjs
vue+mockjs 模拟数据,实现前后端分离开发的更多相关文章
- axios + mock.js模拟数据实现前后端分离开发的实例代码
首先就是必须安装axios和mock.js npm install axios npm install mockjs 1. 然后在文档src中新建一个mock.js文件,如图 2. 在main.js中 ...
- Mock模拟数据,前后端分离
安装 使用npm安装: npm install mockjs; 或直接<script src="http://mockjs.com/dist/mock.js">< ...
- SpringBoot,Vue前后端分离开发首秀
需求:读取数据库的数据展现到前端页面 技术栈:后端有主要有SpringBoot,lombok,SpringData JPA,Swagger,跨域,前端有Vue和axios 不了解这些技术的可以去入门一 ...
- 如何利用vue和php做前后端分离开发?
新手上路,前端工程师,刚毕业参加工作两个月,上面让我用vue搭建环境和php工程师一起开发,做前后端分离,然而我只用过简单的vue做一些小组件的经验,完全不知道怎样和php工程师配合,ps: php那 ...
- beego-vue URL重定向(beego和vue前后端分离开发,beego承载vue前端分离页面部署)
具体过程就不说,是搞这个的自然会动,只把关键代码贴出来. beego和vue前后端分离开发,beego承载vue前端分离页面部署 // landv.cnblogs.com //没有授权转载我的内容,再 ...
- 基于RAP(Mock)实现前后端分离开发
看看RAP的官方定义: 什么是RAP? (Rigel API Platform) 在前后端分离的开发模式下,我们通常需要定义一份接口文档来规范接口的具体信息.如一个请求的地址.有几个参数.参数名称及类 ...
- Web前后端分离开发(CRUD)及其演变概括
今天学习了前后端分离开发模式又从网上查了一些资料就写了一篇博客分享: 一.为什么分离前后端 1.1早期开发 1.2后段为主mvc模式 1.2.1Structs框架介绍 1.2.2Spring mcv开 ...
- Post方式 前后端分离开发postman工具首次使用心得及注意事项
使用前:2009年以前,一直用asp(非asp.net)语言开发网站,网页调用数据等操作,是通过asp标签<%%>嵌入到HTML标签语言中.相隔八年后,听说最近都是MVC后又什么前后端分离 ...
- laravel5.7 前后端分离开发 实现基于API请求的token认证
最近在学习前后端分离开发,发现 在laravel中实现前后台分离是无法无法使用 CSRF Token 认证的.因为 web 请求的用户认证是通过Session和客户端Cookie的实现的,而前后端分离 ...
随机推荐
- arcgis api for js入门开发系列十叠加SHP图层
上一篇实现了demo的热力图,本篇新增叠加SHP图层,截图如下: 叠加SHP图层效果实现的思路如下:利用封装的js文件,直接读取shp图层,然后转换geojson,最后通过arcgis api来解析转 ...
- Java学习笔记--反射API
反射API 1.反射API的介绍 通过反射API可以获取Java程序在运行时刻的内部结构.比如Java类中包含的构造方法.域和方法等元素,并可以与这些元素进行交换. 按照 一般地面向对象的设计 ...
- javascript对象转换,动态属性取值
$(document).ready(function(){ var exceptionMsg = '${exception.message }'; var exceptionstr = ''; //j ...
- PHP提取字符串中的所有汉字
<?php $str = 'aiezu.com 爱E族, baidu.com 百度'; preg_match_all("#[\x{4e00}-\x{9fa5}]#u", $s ...
- Charles抓包工具安装与配置
在实际开发中,我们需要时常抓取线上的请求及数据,甚至是请求的html文档,js,css等静态文件来进行调试.在这里,我使用charles来进行以上操作.但是呢,charles需要进行一系列配置才能达到 ...
- Error detected while processing function CheckFoam256 问题的解决
今天在打开OpenFOAM的constant文件的时候, vim-OpenFOAM-syntax插件遇到了如下问题: Error detected while processing function ...
- Spring+SpringMVC+MyBatis深入学习及搭建(十六)——SpringMVC注解开发(高级篇)
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7085268.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十五)——S ...
- 统计学习方法 三 kNN
KNN (一)KNN概念: K近邻算法是一种回归和分类算法,这主要讨论其分类概念: K近邻模型三要素: 1,距离: 2,K值的选择: K值选择过小:模型过复杂,近似误差减小,估计误差上升,出现过拟合 ...
- Dagger2在Android开发中的应用
世界是普遍联系的,任何事物和个体都直接或间接相互依赖,在时空长河中共同发展.在面向对象的世界中,更是如此,类与类之间的依赖,关联关系,模块(亦或是分层架构中的层)之间的耦合关系,都是我们在软件开发实践 ...
- ASP.NET MVC Autofac依赖注入的一点小心得(包含特性注入)
前言 IOC的重要性 大家都清楚..便利也都知道..新的ASP.NET Core也大量使用了这种手法.. 一直憋着没写ASP.NET Core的文章..还是怕误导大家.. 今天这篇也不是讲Core的 ...