使 用 M o c k 模 拟 后 端 ( V u e 集 成 M o c k ) 使用Mock模拟后端(Vue集成Mock) 使用Mock模拟后端(Vue集成Mock)
先建立子模块
再在index.js中注册子模块
官网:http://mockjs.com/
当前端工程师需要独立于后端并行开发时,后端接口还没有完成,那么前端怎么获取数据?
这时可以考虑前端搭建web server自己模拟假数据,这里我们选第三方库mockjs用来生成随机数据,拦截Ajax请求。
1.安装
npm install mockjs --save-dev
# 使用axios发送ajax请求
npm install axios --save
# 使用mockjs产生随机数据
npm install mockjs --save-dev
# 使用json5解决json文件,无法添加注释的问题
npm install json5 --save-dev
2.在项目目录下新建mock文件夹
3.新建测试文件testMock.js
const Mock = require('mockjs')
let id = Mock.mock('@id')
console.log(id)
const Mock = require('mockjs')
let id = Mock.mock('@id')
console.log(id)
let obj = Mock.mock({
id:'@id'
})
console.log(obj)
var obj2 = Mock.mock({
id:"@id()",
username:"@cname()",
date:"@date()",
avator:"@image('300x300','red','#fff','avator')",
description:"@paragraph()",
ip:"@ip()",
email:"@email()"
})
console.log(obj2)
4.使用json5模拟实际数据存储
安装插件
const fs = require('fs')
const path = require('path')
const JSON5 = require('json5')
var json = fs.readFileSync(path.join(__dirname,'./user.json5'),'utf-8')
console.log(json)
var obj = JSON5.parse(json)
console.log(obj)
5.mock和vue-cli结合
5.1 新建index.js
import Mock from 'mockjs'
Mock.mock('/api/goodslist','get',{
status:200,
message:'获取商品列表成功!',
data:[1,2,3,6]
})
5.2 在main.js中导入Mock
import Vue from 'vue'
import App from './App.vue'
import router from "./routes"
import auth from "./utils/auth"
import axios from 'axios'
Vue.config.productionTip = false
// 使Mock生效
import '../mock/'
Vue.prototype.$auth = auth
Vue.prototype.$http = axios
new Vue({
render: h => h(App),
router
}).$mount('#app')
5.3路由配置
import VueRouter from "vue-router"
import Vue from "vue"
import MockTest from '@/components/MockTest'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{
path: "/",
component: MockTest,
name:"mocktest"
}
]
})
export default router
5.4测试MockTest.vue
<template>
<div class="">
<button @click="getGoodsList">获取商品列表</button>
</div>
</template>
<script type="text/ecmascript-6">
export default {
methods:{
async getGoodsList(){
const {data:res} = await this.$http.get('/api/goodslist')
console.log(res)
}
}
}
</script>
<style scoped lang='scss'>
</style>
5.5测试结果
6.介绍Mock的随机函数
import Mock from 'mockjs'
Mock.mock('/api/goodslist','get',{
status:200,
message:'获取商品列表成功!',
data:[{
id:0,
name:'草莓',
price:10,
count:200,
img:'url_address',
}]
})
import Mock from 'mockjs'
Mock.mock('/api/goodslist','get',{
status:200,
message:'获取商品列表成功!',
'data|5':[{
id:'@increment(1)',
name:'@cword(2,8)',
price:'@natural(2,5)',
count:'@natural(100,999)',
img:'dataImage(300x300)',
}]
})
import Mock from 'mockjs'
Mock.mock('/api/goodslist','get',{
status:200,
message:'获取商品列表成功!',
'data|5-20':[{
id:'@increment(1)',
name:'@cword(2,8)',
price:'@natural(2,5)',
count:'@natural(100,999)',
img:'dataImage(300x300)',
}]
})
7.使用Mock模拟Post请求
import Mock from 'mockjs'
Mock.mock('/api/goodslist','get',{
status:200,
message:'获取商品列表成功!',
'data|5':[{
id:'@increment(1)',
name:'@cword(2,8)',
price:'@natural(2,5)',
count:'@natural(100,999)',
img:'dataImage(300x300)',
}]
})
Mock.mock('/api/addgoods','post',function(option){
console.log(option)
return{
status:200,
message:'商品添加成功!'
}
})
<template>
<div class="">
<button @click="getGoodsList">获取商品列表</button>
<button @click="addGoods">添加商品</button>
</div>
</template>
<script type="text/ecmascript-6">
export default {
methods:{
async getGoodsList(){
const {data:res} = await this.$http.get('/api/goodslist')
console.log(res)
},
async addGoods(){
const {data:res} = await this.$http.post('/api/addgoods',{
name:'草莓',
price:8,
count:100,
img:'',
})
console.log(res)
}
}
}
</script>
<style scoped lang='scss'>
</style>
Mock.mock('/api/addgoods','post',function(option){
console.log(option)
return Mock.mock({
status:200,
message:'@cword(2,5)'
})
})
8.使用Mock模拟带参数的URL请求
<template>
<div class="">
<button @click="getGoodsList">获取商品列表</button>
<button @click="addGoods">添加商品</button>
<button @click="getGoodsById">根据Id获取商品信息</button>
</div>
</template>
<script type="text/ecmascript-6">
export default {
methods:{
async getGoodsList(){
const {data:res} = await this.$http.get('/api/goodslist')
console.log(res)
},
async addGoods(){
const {data:res} = await this.$http.post('/api/addgoods',{
name:'草莓',
price:8,
count:100,
img:'',
})
console.log(res)
},
async getGoodsById(){
const {data:res} = await this.$http.get('/api/getgoods/1')
console.log(res)
}
}
}
</script>
<style scoped lang='scss'>
</style>
import Mock from 'mockjs'
Mock.mock('/api/goodslist','get',{
status:200,
message:'获取商品列表成功!',
'data|5':[{
id:'@increment(1)',
name:'@cword(2,8)',
price:'@natural(2,5)',
count:'@natural(100,999)',
img:'dataImage(300x300)',
}]
})
Mock.mock('/api/addgoods','post',function(option){
console.log(option)
return Mock.mock({
status:200,
message:'@cword(2,5)'
})
})
Mock.mock('/api/getgoods/1','get',{
data:{
id:9,
name:'苹果',
price:5,
count:9090,
img:''
},
status:200,
message:"成功!"
})
参数可变
<template>
<div class="">
<button @click="getGoodsList">获取商品列表</button>
<button @click="addGoods">添加商品</button>
<button @click="getGoodsById(2)">根据Id获取商品信息</button>
</div>
</template>
<script type="text/ecmascript-6">
export default {
methods:{
async getGoodsList(){
const {data:res} = await this.$http.get('/api/goodslist')
console.log(res)
},
async addGoods(){
const {data:res} = await this.$http.post('/api/addgoods',{
name:'草莓',
price:8,
count:100,
img:'',
})
console.log(res)
},
async getGoodsById(id){
const {data:res} = await this.$http.get(`/api/getgoods/${id}`)
console.log(res)
}
}
}
</script>
<style scoped lang='scss'>
</style>
Mock.mock(/\/api\/getgoods/,'get',{
data:{
id:1,
name:'Major',
price:9999999,
count:1,
img:''
},
status:200,
message:"成功!"
})
Mock.mock(/\/api\/getgoods/,'get',function(option){
console.log(option)
// 通过正则的.exec()函数
const res = /\/api\/getgoods\/(\d+)/.exec(option.url)
return Mock.mock({
data:{
id:res[1]-0,
name:'苹果',
price:5,
count:9090,
img:'@dataImage(2x2)',
},
status:200,
message:"成功!"
})
})
exec与test的区别,exec可以返回数据,而test只能判断
9.自定义随机函数
import Mock, { Random } from 'mockjs'
// 创建自定义Mock函数
Random.extend({
// 自定义函数名:function 函数
fruit:function(){
const arr = ['苹果','梨','菠萝','草莓']
return this.pick(arr)
}
})
Mock.mock(/\/api\/getgoods/,'get',function(option){
console.log(option)
// 通过正则的.exec()函数
const res = /\/api\/getgoods\/(\d+)/.exec(option.url)
return Mock.mock({
data:{
id:res[1]-0,
name:'@fruit',
price:5,
count:9090,
img:'@dataImage(2x2)',
},
status:200,
message:"成功!"
})
})
10.Mock结构重组
extend.js
import { Random } from 'mockjs'
// 创建自定义Mock函数
Random.extend({
// 自定义函数名:function 函数
fruit:function(){
const arr = ['苹果','梨','菠萝','草莓']
return this.pick(arr)
}
})
goods.js
import Mock from 'mockjs'
Mock.mock(/\/api\/getgoods/,'get',function(option){
console.log(option)
// 通过正则的.exec()函数
const res = /\/api\/getgoods\/(\d+)/.exec(option.url)
return Mock.mock({
data:{
id:res[1]-0,
name:'@fruit',
price:5,
count:9090,
img:'@dataImage(2x2)',
},
status:200,
message:"成功!"
})
})
Mock.mock('/api/goodslist','get',{
status:200,
message:'获取商品列表成功!',
'data|5':[{
id:'@increment(1)',
name:'@cword(2,8)',
price:'@natural(2,5)',
count:'@natural(100,999)',
img:'dataImage(300x300)',
}]
})
Mock.mock('/api/addgoods','post',function(option){
console.log(option)
return Mock.mock({
status:200,
message:'@cword(2,5)'
})
})
Mock.mock('/api/getgoods/1','get',{
data:{
id:9,
name:'苹果',
price:5,
count:9090,
img:''
},
status:200,
message:"成功!"
})
index.js
import './extends'
// 导入商品模块
import './goods'
// 导入用户模块
练习案例:
1.准备API接口文档
2.编写brand_test.js文件,并将其导入
brand_test.js
import Mock from 'mockjs'
Mock.mock('/api/getprodlist','get',{
status:0,
'message|4':[
{
id:'@increment(1)',
name:'@cword(3,5)',
ctime:new Date()
}
]
})
index
import './extends'
// 导入商品模块
import './goods'
// 导入模块
import './brand_list'
编写MockTest.vue
<template>
<div class="">
<h1 class="title">练习案例</h1>
<el-row :gutter="10">
<el-col :span="8">
<el-input placeholder="请输入内容" size="mini" >
<template slot="prepend">品牌名称</template>
</el-input>
</el-col>
<el-col :span="4">
<el-button type="primary" size="mini">添加</el-button>
</el-col>
</el-row>
<!-- 表格区域 -->
<el-table :data="brandlist" style="width: 100%;margin-top :10px" border size="mini" >
<el-table-column prop="id" label="Id"> </el-table-column>
<el-table-column prop="name" label="Name"> </el-table-column>
<el-table-column prop="ctime" label="Ctime"> </el-table-column>
<el-table-column label="操作">
<template v-slot="scope">
<el-button type="danger" size="mini">删除--{{scope.row.id}}</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script type="text/ecmascript-6">
import axios from "axios"
export default {
name: "",
data() {
return {
brandlist:{}
}
},
components:{},
mounted(){
axios.get("/api/getprodlist").then(res=>{
const data = res.data;
console.log(data)
this.brandlist = data.message
}).catch(err =>{
console.log(err);
})
}
}
</script>
<style scoped lang='scss'>
.title{
font-size: 18px;
text-align: center;
}
</style>