mockjs文档:Mock.js
1.下载mockjs
npm install mockjs --save //开发环境
2.在src下新建mock文件并导入index.js
import Mock from "mockjs";const { newsList } = Mock.mock({"newsList|75": [{id: "@increment",title: "@ctitle()",content: "@cparagraph(5,10)",img_url: "@image('50*50','#FF83FA','#FCFCFC','png','mono')",add_time: "@date(yyyy-MM-dd hh:mm:ss)",},],});console.log(newsList);var getQuery = (url, name) => {console.log(url, name);const index = url.indexOf("?");if (index !== -1) {const queryStrArr = url.substr(index + 1).split("&");for (var i = 0; i < queryStrArr.length; i++) {const itemArr = queryStrArr[i].split("=");console.log(itemArr);if (itemArr[0] === name) {return itemArr[1];}}}return null;};// 定义获取新闻列表的数据// /api/get/news?pageinde1&pagesize=10Mock.mock(/\/api\/get\/news/, "get", (options) => {// 获取传递参数pageindex,pagesizeconst pageindex = getQuery(options.url, "pageindex");const pagesize = getQuery(options.url, "pagesize");console.log(pageindex);console.log(pagesize);const start = (pageindex - 1) * pagesize;const end = pagesize * pageindex;const totalPage = Math.ceil(newsList.length / pagesize);// pageindex:1 pagesize:10 返回0-9条数据 2-10-(10-19) 3-10(20-29)// 数据的起始位置:(pageindex-1)*pagesize 结束位置:pageindex*pagesizeconst list = pageindex > totalPage ? [] : newsList.slice(start, end);return {status: 200,message: "获取新闻列表成功",list: list,total: totalPage,};});// 定义添加新闻的数据Mock.mock("/api/add/news", "post", (options) => {const body = JSON.parse(options.body);console.log(body);newsList.push(Mock.mock({id: "@increment",title: body.title,content: body.content,img_url: "@image('50*50','#FF83FA','#FCFCFC','png','mono')",add_time: "@date(yyyy-MM-dd hh:mm:ss)",}));return {status: 200,message: "添加成功",list: newsList,total: newsList.length,};});// 定义删除新闻Mock.mock("/api/delete/news", "post", (options) => {console.log(options);const body = JSON.parse(options.body);console.log(body);const index = newsList.findIndex((item) => {return item.id === body.id;});newsList.splice(index, 1);console.log(index);return {status: 200,message: "添加成功",list: newsList,total: newsList.length,};});console.log(Mock);
3.在main.js中new Vue实例前导入并判断开发环境下的 mockjs
if(process.env.NODE_ENV === 'development') {require('./mock/index.js')}
4.在页面中使用mockjs数据
<template><div><!-- 搜索 --><div class="add"><input type="text" v-model="title" placeholder="输入标题" /><input type="text" v-model="content" placeholder="输入内容" /><button @click="add">添加</button></div><!-- 表格--><div class="news_list"><table><tr><th>图片</th><th>标题</th><th>内容</th><th>时间</th><th>操作</th></tr><tr v-for="item in list" :key="item.id"><td><img :src="item.img_url" alt="" /></td><td>{{ item.title }}</td><td>{{ item.content }}</td><td>{{ item.add_time }}</td><td><button class="remove" @click="remove(item.id)">删除</button></td></tr></table></div><!-- 上下页 --><div class="pages"><button @click="prevPage">上一页</button><button @click="nextPage">下一页</button></div></div></template><script>import axios from "axios";export default {data() {return {title: "",content: "",list: [],pageindex: 1,title: "",content: "",};},methods: {add() {// if (this.title.trim() === "" || this.content.trim() === "")// return alert("请添加那些新闻标题和内容");// console.log(this.title, this.content);axios.post("/api/add/news", {title: this.title,content: this.content,}).then((res) => {console.log(res);});},//获取新闻列表数据getNewsList() {axios.get("/api/get/news", {params: {pageindex: this.pageindex,pagesize: 10,},}).then((res) => {console.log(res);this.list = res.data.list;});},nextPage() {this.pageindex++;this.getNewsList();},prevPage() {this.pageindex--;this.getNewsList();},// 删除新闻remove(id) {// console.log(id);axios.post("/api/delete/news", {id,}).then((res) => {console.log(res);});},},created() {this.getNewsList();},mounted() {},};</script><style>.add input {border-radius: 5px;border: none;outline: none;border: 1px solid #999;padding: 5px;margin-right: 5px;}button {width: 100px;height: 30px;background: #409eff;color: none;outline: none;border-radius: 5px;margin-left: 5px;cursor: pointer;border: 0;color: #fff;}.news_list {width: 1220px;height: 495px;overflow-y: scroll;overflow-x: hidden;margin: 10px;}table {border-collapse: collapse;height: 495px;overflow-y: scroll;overflow-x: hidden;margin: 10px;border: 1px solid rgb(94, 92, 92);}table th {font-size: 16px;height: 30px;width: 224px;font-weight: normal;border: 1px solid rgb(94, 92, 92);}table td {font-size: 12px;padding: 5px;border: 1px solid rgb(94, 92, 92);}table td:nth-child(4) {width: 150px;}table td:nth-child(2) {min-width: 100px;}table img {width: 80px;height: 80px;}table .remove {background: #f56c6c;}</style>
扩展
mockjs一些API:
mockjs使用mockjs项目安装mocknpm install mockjs项目中新建mock文件//引入mock模块import Mock from 'mockjs'将mock文件在main.js中导入import Vue from 'vue'import App FROM './App.vue'import './mock/index.js'Vue.config.productionTip = falsenew Vue({render:h => h(App),}).$mount('#app')mock语法生成字符串生成指定次数字符串import Mock from 'mockjs'const data = Mock.mock({"string|4":"哈哈"})生成指定范围长度字符串const data = Mock.mock({"string|1-8":"哈哈"})生成文本生成一个随机字符串const data = Mock.mock({"string":"@cword"}) 生成指定长度和范围const data = Mock.mock({string:"@cword(1)"str :"@cword(10,15)"})生成标题和句子生成标题和句子const data = Mock.mock({title:"@ctitle(8)"sentence:"@csentence"})生成指定长度的标题和句子const data = Mock.mock({title:"@ctitle(8)"sentence:"@csentence(50)"})生成指定范围的const data = Mock.mock({title:"@ctitle(5,8)"sentence:"@csentence(50,100)"})生成段落随机生成段落const data = Mock.mock({content:"@cparagraph()"})生成数字生成指定数字const data = Mock.mock({"number|80":1})生成范围数字const data = Mock.mock({"number|1-99":1})生成自增id随机生成标识const data = Mock.mock({id:"@increment"})生成姓名-地址-身份证随机生成姓名-地址-身份证const data = Mock.mock({name:"@cname()"idCard:"@id()"address:"@city(true)"})随机生成图片生成图片:@image(“300*200”,‘#ff0000','#fff','gif','坤坤')参数1:图片大小['300*250','250*250','240*400','336*280''180*150','720*300','468*60','234*60''388*31','250*250','240*400','120*40''125*125','250*250','240*400','336*280']参数2:图片背景色参数3:图片前景色参数4:图片格式参数5:图片文字生成时间@Date生成指定格式时间:@date(yyyy-MM-dd hh:mm:ss)指定数组返回的参数指定长度:‘date|5’指定范围:'data|5-10'const data = Mock.mock({'list|50-99':[{name:'@cname'address:'@city(true)'id:'@increment()'}]})mock拦截请求定义get请求Mock.mock('api/get/news','get',()=>{return{status:200,message:"获取数据成功"}})定义post请求Mock.mock('api/post/news','post',()=>{return{status:200,message:"获取数据成功"}})实现新闻管理案例获取数据接口地址::/api/get/news接口参数:pageindex:页码pagesize:每页的条数请求类型:get返回的数据:{status:200,message:"获取新闻列表成功",list:[{"id":1,"title":"解忧杂货店","content":"《解忧杂货店》是日本作家东野圭吾写作的长篇小说。《小说野性时代》连载,于3月由角川书店发行单行本","img_url":"/it/u=2090705107,20534764&fm=224&app=112&f=JPEG?w=500&h=500&s=61D0718656561FFFE504A51703000067","add_time":"1984-04-03 11:43:37"}],total:50}}添加新闻接口地址::/api/add/news接口参数:title:'标题'content:内容请求类型:post返回的数据:{status:200,message:"获取新闻列表成功",list:[{"id":1,"title":"解忧杂货店","content":"《解忧杂货店》是日本作家东野圭吾写作的长篇小说。《小说野性时代》连载,于3月由角川书店发行单行本","img_url":"/it/u=2090705107,20534764&fm=224&app=112&f=JPEG?w=500&h=500&s=61D0718656561FFFE504A51703000067","add_time":"1984-04-03 11:43:37"}],total:50}}删除新闻接口地址::/api/delete/news接口参数:id;新闻id请求类型:post返回的数据:{status:200,message:"获取新闻列表成功",list:[{"id":1,"title":"解忧杂货店","content":"《解忧杂货店》是日本作家东野圭吾写作的长篇小说。《小说野性时代》连载,于3月由角川书店发行单行本","img_url":"/it/u=2090705107,20534764&fm=224&app=112&f=JPEG?w=500&h=500&s=61D0718656561FFFE504A51703000067","add_time":"1984-04-03 11:43:37"}],total:50}}