vue mock数据(模拟后台)
本文转载自:https://blog.csdn.net/benben513624/article/details/78562529
vue实现ajax获取后台数据是通过vue-resource,首先通过npm安装vue-resource
npm install vue-resource --save
安装完成以后,把vue-resource引入到main.js文件中
src/main.js
// 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 VueResource from 'vue-resource'
import Layout from './components/layout' Vue.use(VueResource);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<Layout/>',
components: { Layout }
})
把vue-resource引入项目以后,就可以在任何组件里面直接用了
<template>
<div class="index-wrap">
<div class="index-left">
<div class="index-left-block lastest-news">
<h2>最新消息</h2>
<ul>
<li v-for="news in newsList">
<a :href="news.url" class="new-item">{{news.title}}</a>
</li>
</ul>
</div>
</div>
<div class="index-right">
</div>
</div>
</template>
<script type="text/ecmascript-6">
export default{
created(){
this.$http.get('api/getNewsList').then((res)=>{ //可用post请求,this.$http.post('api/getNewsList',{'userId':123})
console.log(res.data);
this.newsList=res.data;
console.log( this.newsList);
},(err)=>{
console.log(err);
});
},
data(){
return {
newsList:[], }
}
}
</script>
<style scoped>
.index-wrap{
width: 1200px;
margin: auto;
overflow: hidden;
background: blue;
}
.index-left{
float: left;
width: 300px;
text-align: left;
background: red;
}
.index-right {
float: left;
width: 900px;
}
.index-left-block{
margin: 15px;
background: #fff;
box-shadow: 1px #ddd;
}
.index-left-block .hr {
margin-bottom: 20px;
border-bottom: 1px solid #ddd;
}
.index-left-block h2 {
background: #4fc08d;
color: #fff;
padding: 10px 15px;
margin-bottom: 20px;
}
.index-left-block h3 {
padding: 15px 5px 15px;
font-weight: bold;
color: #;
}
.index-left-block ul {
padding: 10px 15px;
}
.index-left-block li {
padding: 5px;
}
.hot-tag{
background: red;
color:#fff;
font-size: 10px;
border-radius: 10px;
} </style>
上面这个就是用vue-resource来进行数据请求的大体流程,作为前端,在开发的过程,遇到这种调用后端接口调试起来还是很麻烦的,我们要找后端的一个服务器,然后关联起来 ,或者把前端代码放上去,这样都是挺麻烦的,解决的办法就是前端放mock data,主要有两种方式:
(1)json-server模拟数据
使用json-server这个工具,可以虚构出后端接口对应的数据,然后在项目里发送特定的请求,就可以发请求拿到模拟的数据,首先npm安装
npm install json-server --save
然后在build/webpack.dev.conf.js中进行配置,参考json-server
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder') const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool, // these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: true,
hot: true,
host: process.env.HOST || config.dev.host,
port: process.env.PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay ? {
warnings: false,
errors: true,
} : false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
]
})
//这里是json-server配置信息
// json-server.js
const jsonServer = require('json-server')
const apiServer = jsonServer.create()
const apiRouter = jsonServer.router('db.json') //数据关联server,db.json与index.html同级
const middlewares = jsonServer.defaults() apiServer.use(middlewares)
apiServer.use('/api',apiRouter)
apiServer.listen(, () => { //监听端口
console.log('JSON Server is running')
}) module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port // Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${config.dev.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
})) resolve(devWebpackConfig)
}
})
})
配置完成以后,npm run dev 启动,浏览器输入localhost:3000,出现如下图,说明配置成功

那么现在还有一个问题,我们代码的服务端接口是8080,json-server的服务端端口是3000,由于浏览器的同源策略问题,这样请求会存在一个跨域问题,所以这里要做一个服务端代理的配置,配置build/index.js中的proxyTable:
host: 'localhost', // can be overwritten by process.env.HOST
port: , // can be overwritten by process.env.HOST, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
proxyTable:{
'/api/':'http://localhost:3000/'
},
这样就可以在localhost:8080下访问接口了

(2)express启动数据服务
在实际开发中,发现json-server只能用于get请求,不能进行post请求,在网上找的另外一种方法,express既能用于get请求,又能用于post请求,下面说一下express启动服务的配置方法:
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
var express = require('express')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder') const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool, // these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: true,
hot: true,
host: process.env.HOST || config.dev.host,
port: process.env.PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay ? {
warnings: false,
errors: true,
} : false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
]
}) // json-server.js
//const jsonServer = require('json-server')
//const apiServer = jsonServer.create()
//const apiRouter = jsonServer.router('db.json')
//const middlewares = jsonServer.defaults()
//
//apiServer.use(middlewares)
//apiServer.use('/api',apiRouter)
//apiServer.listen(3000, () => {
// console.log('JSON Server is running')
//})
//express 配置server
var apiServer = express()
var bodyParser = require('body-parser')
apiServer.use(bodyParser.urlencoded({ extended: true }))
apiServer.use(bodyParser.json())
var apiRouter = express.Router()
var fs = require('fs')
apiRouter.route('/:apiName') //接口路径
.all(function (req, res) {
fs.readFile('./db.json', 'utf8', function (err, data) { //读取接口文件
if (err) throw err
var data = JSON.parse(data)
if (data[req.params.apiName]) {
res.json(data[req.params.apiName])
}
else {
res.send('no such api name')
} })
}) apiServer.use('/api', apiRouter);
apiServer.listen(, function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:' + + '\n')
}) module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port // Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${config.dev.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
})) resolve(devWebpackConfig)
}
})
})
在浏览器中输入接口地址,如下:

vue mock数据(模拟后台)的更多相关文章
- Vue+Mock.js模拟登录和表格的增删改查
有三类人不适合此篇文章: "喜欢站在道德制高点的圣母婊" -- 适合去教堂 "无理取闹的键盘侠" -- 国际新闻版块欢迎你去 "有一定基础但又喜欢逼逼 ...
- vue mock数据设置
1.新建mock文件夹 2.添加你需要的数据例如新建商品表goods.json { "status":"0", "result":[ { & ...
- vue 项目初始化、mock数据以及安装less
vue 创建一个项目 1.首先建立一个空文件夹,然后将这个文件夹要放到码云或者其他代码管理平台. 例如码云: 在码云上建立一个项目,然后在控制台进入这文件夹执行 git clone 地址是码云上创建的 ...
- 深入浅出的webpack4构建工具--webpack4+vue+vuex+mock模拟后台数据(十九)
mock的官网文档 mock官网 关于mockjs的优点,官网这样描述它:1)可以前后端分离.2)增加单元测试的真实性(通过随机数据,模拟各种场景).3)开发无侵入(不需要修改既有代码,就可以拦截 A ...
- vue mock(模拟后台数据) +axios 简单实例(二)
需装上axios,build文件夹中webpack.dev.conf.js文件添加上vue mock配置的东东, 如,继(一) //组件<template> <div> &l ...
- Vue笔记:使用 mock.js 模拟数据
在我们的项目实际开发过程中,后端的接口往往是较晚才会提供出来,并且还要写接口文档,如果前端的开发都要等到接口开发完成才开始就非常影响项目整体开发进度了,mock.js 的出现使前后端分离并行开发成为可 ...
- mock数据(模拟后台数据)
mock数据(模拟后台数据) - Emily恩 - 博客园 https://www.cnblogs.com/enboke/p/vue.html Mock.js http://mockjs.com/ 前 ...
- vue项目中使用mockjs+axios模拟后台数据返回
自己写练手项目的时候常常会遇到一个问题,没有后台接口,获取数据总是很麻烦,于是在网上找了下,发现一个挺好用的模拟后台接口数据的工具:mockjs.现在把自己在项目中使用的方法贴出来 先看下项目的目 ...
- vue从mock数据过渡到使用后台接口
说明: 最近在搭建一个前端使用vue-element-admin,后端使用springBoot的项目. 由于vue-element-admin使用的是mock的模拟数据跑起来的项目,所以在开发过程中难 ...
随机推荐
- day 107radis非关系型数据库
http://www.cnblogs.com/wupeiqi/articles/5132791.html 参考邮件. radis : 1. NoSql 2. 缓存在内存中 3.支持数据持久化 二. ...
- T1387:搭配购买(buy)
[题目描述] Joe觉得云朵很美,决定去山上的商店买一些云朵.商店里有n朵云,云朵被编号为1,2,…...,n,并且每朵云都有一个价值.但是商店老板跟他说,一些云朵要搭配来买才好,所以买一朵云则与这朵 ...
- MongoDB Windows之ZIP安装
下载.下载地址同MSI下载地址:https://www.mongodb.com/download-center/community .Package选择Zip. 下载完成后解压到对应文件夹,该文件夹就 ...
- Spring Boot开启的2种方式
Spring Boot依赖 使用Spring Boot很简单,先添加基础依赖包,有以下两种方式 1. 继承spring-boot-starter-parent项目 <parent> < ...
- 控制 if 语句 while循环 break continue
if 语句的语法: 1. if 条件 : #引号是将条件与结果分开 代码块 # 四个空格,或者一个tab键,这个是告诉程序满足这个条件的 说明: 当条件成立的时候(True), 代码块会被执行 ...
- 选择 NoSQL 需要考虑的 10 个问题
那么我为什么要写这篇文章呢? 是因为我认为NoSQL解决方案不如RDBMS解决方案吗?当然不! 是因为我专注于SQL的做事方式,而不想陷入一种相对较新的技术的不确定性吗?不,也不是!事实上,我非常兴奋 ...
- 【问题解决方案】本地仓库删除远程库后添加到已有github仓库时仓库地址找不到的问题(github仓库SSH地址)
参考: 我参考我自己.jpg 背景: 想添加一下远程库,github主页找了半天,Google搜索了半天,都没有找到,所以这里写一个,记录一下 1-格式分析:git@github.com:用户名/仓库 ...
- Java8 新增BASE64加解密API
什么是Base64编码? Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法 基于64个字符A-Z,a-z,0-9,+,/ ...
- Codeforces 364D 随机算法
题意:给你一个序列,定义ghd为一个序列中任意n / 2个数的gcd中最大的那个,现在问这个序列的ghd为多少. 思路:居然是论文题...来自2014年国家集训队论文<随机化算法在信息学竞赛中的 ...
- Codeforces 1188B 式子转化
思路:看到(a + b)想到乘上(a - b)变成平方差展开(并没有想到2333), 两边同时乘上a - b, 最后式子转化成了a ^ 4 - ka = b ^ 4 - kb,剩下的就水到渠成了. 0 ...