IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> 前端Vue使用封装Mock.js和api请求模拟数据案例(带源码) -> 正文阅读

[JavaScript知识库]前端Vue使用封装Mock.js和api请求模拟数据案例(带源码)

一:准备阶段

1.安装mockjs axios

npm install mockjs --save
npm install axios --save

2.main.js全局引入

import './utils/mock'//此部分引入的是我们所编写的mockjs文档
import axios from 'axios'
Vue.prototype.$axios = axios

二:使用阶段

1.src下面创建api文件里面在创建request.js封装好的api,代码如下:
import axios from ‘axios’

// 案例!!!!!
export function getCase() {
  return axios.get('/api/case')
}

// 文本列表
export function county() {
  return axios.get('/api/getObject')
}

// 折线数据
export function getList() {
  return axios.post('/api/line')
}

// home折线数据
export function getLine() {
  return axios.post('/api/lineAdd')
}



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 {
  mockdata(url, params) {
    return fetch(url, params);
  }
}

2.src下面创建utils文件里面在创建mock.js封装好的模拟数据库,写接口造数据地方代码如下:
官方文档mock.js更多数据案例: http://mockjs.com/examples.html

import Mock from 'mockjs'
// 案例!!!!和详解意思,还是不懂看文档
Mock.mock('/api/case', 'get', () => {
  return Mock.mock({
    "mtime": "@datetime", //随机生成日期时间
    "score|1-800": 800, //随机生成1-800的数字
    "rank|1-100": 100, //随机生成1-100的数字
    "stars|1-5": 5, //随机生成1-5的数字
    "nickname": "@cname", //随机生成中文名字
  })
})

// 返回字符串
Mock.mock('/api/data', 'get', () => {
  return Mock.mock({
    'string|3': '*' //  string 代表字符串名称  后面3代表个数
  })
})

// 返回指定范围的整数
Mock.mock('/api/getInteger', () => {
  return Mock.mock({
    'a|1-100': 100 // 
  })
})

// 返回随机数组
Mock.mock('/api/getArr', () => {
  return Mock.mock({
    'data|1-30': [{
      'name': '张三'
    }]
  })
})

// 返回随机字符
Mock.mock('/api/getRandom1', () => {
  return Mock.mock({
    'random1': /[a-z]{2}[A-Z]{2}[0-9]/
  })
})

// 返回随机字符
Mock.mock('/api/getRandom2', () => {
  return Mock.mock({
    random2: '@string("lower", 5)'
  })
})

// 返回UUID
Mock.mock('/api/getUUID', () => {
  return {
    'uuid': Mock.Random.id()
  }
})


// 返回随机个数的对象
Mock.mock('/api/getObject', () => {
  return Mock.mock({
    'list|10': [{
      'id|+1': 1,
      'classroom|1': ['精品语文班', '精品作业A班', '英语班', '语文班'],
      'from|1': ['到店咨询', '微店', '壹家教', '学习服务平台'],
      'status|1': ['意识强烈', '预报名', '意向一般', '暂无意向'],
    }],
    name: Mock.Random.cname(), //随机产生一个中文的姓名
    addr: Mock.mock('@county(true)'), //随机生成一个地址
    'age|18-60': 1, //随机生成一个数字 大小在18到60
    birth: Mock.Random.date(), //随机生成一个日期
    sex: Mock.Random.integer(0, 1), //随机生成一个整数,0/1 ,根据这个来给“男” “女”
    email: Mock.mock('@EMAIL()'), //随机生成一个邮箱
    'moblie|1': ['13531544954', '13632250649', '15820292420', '15999905612'], //在数组中随机找一个
    'num1|1-100.2': 1, //1-100 中随机生成一个保留两位小数点
    'num2|100-300.2': 1,
    'classroom|1': ['精品语文班', '精品作业A班', '英语班', '语文班'],
    'from|1': ['到店咨询', '微店', '壹家教', '学习服务平台'],
    'status|1': ['意识强烈', '预报名', '意向一般', '暂无意向'],
    time: Mock.Random.date('yyyy-MM-dd'),
    mobile: /^1[0-9]{10}$/ //用正则匹配1开头的11位数字的手机号
  })
})



// 第二种~~~~~
// const cateData = {"data":[{"all":484,"children":[{"all":120,"pid":10000,"quesId":10001,"quesName":"武汉"},{"all":100,"pid":10000,"quesId":10002,"quesName":"鄂州"},{"all":90,"pid":10000,"quesId":10003,"quesName":"咸宁"},{"all":66,"pid":10000,"quesId":10004,"quesName":"黄冈"},{"all":88,"pid":10000,"quesId":10005,"quesName":"荆州"}],"pid":1,"quesId":10000,"quesName":"湖北"},{"all":450,"children":[{"all":100,"pid":11000,"quesId":11001,"quesName":"广州"},{"all":200,"pid":11000,"quesId":11002,"quesName":"惠州"},{"all":70,"pid":11000,"quesId":11003,"quesName":"珠海"},{"all":80,"pid":11000,"quesId":11004,"quesName":"佛山"}],"pid":1,"quesId":11000,"quesName":"广东"},{"all":243,"children":[{"all":88,"pid":12000,"quesId":12001,"quesName":"杭州"},{"all":100,"pid":12000,"quesId":12002,"quesName":"宁波"},{"all":20,"pid":12000,"quesId":12003,"quesName":"温州"},{"all":35,"pid":12000,"quesId":12004,"quesName":"嘉兴"}],"pid":1,"quesId":12000,"quesName":"浙江"},{"all":285,"children":[{"all":220,"pid":13000,"quesId":13001,"quesName":"成都"},{"all":20,"pid":13000,"quesId":13002,"quesName":"雅安"},{"all":45,"pid":13000,"quesId":13003,"quesName":"绵阳"}],"pid":1,"quesId":13000,"quesName":"四川"},{"all":235,"children":[{"all":75,"pid":14000,"quesId":14001,"quesName":"济南"},{"all":90,"pid":14000,"quesId":14002,"quesName":"青岛"},{"all":40,"pid":14000,"quesId":14003,"quesName":"烟台"},{"all":30,"pid":14000,"quesId":14004,"quesName":"威海"}],"pid":1,"quesId":14000,"quesName":"山东"},{"all":285,"children":[{"all":120,"pid":15000,"quesId":15001,"quesName":"台北"},{"all":60,"pid":15000,"quesId":15002,"quesName":"桃园"},{"all":50,"pid":15000,"quesId":15003,"quesName":"高雄"},{"all":55,"pid":15000,"quesId":15004,"quesName":"新竹"}],"pid":1,"quesId":15000,"quesName":"台湾"},{"all":595,"children":[{"all":220,"pid":16000,"quesId":16001,"quesName":"南京"},{"all":110,"pid":16000,"quesId":16002,"quesName":"无锡"},{"all":150,"pid":16000,"quesId":16003,"quesName":"苏州"},{"all":80,"pid":16000,"quesId":16004,"quesName":"连云港"},{"all":35,"pid":16000,"quesId":16005,"quesName":"盐城"}],"pid":1,"quesId":16000,"quesName":"江苏"},{"all":760,"children":[{"all":150,"pid":17000,"quesId":17001,"quesName":"黄埔"},{"all":120,"pid":17000,"quesId":17002,"quesName":"徐汇"},{"all":100,"pid":17000,"quesId":17003,"quesName":"静安"},{"all":130,"pid":17000,"quesId":17004,"quesName":"普陀"},{"all":100,"pid":17000,"quesId":17005,"quesName":"虹口"},{"all":100,"pid":17000,"quesId":17006,"quesName":"闵行"},{"all":60,"pid":17000,"quesId":17007,"quesName":"嘉定"}],"pid":1,"quesId":17000,"quesName":"上海"},{"all":900,"children":[{"all":240,"pid":18000,"quesId":18001,"quesName":"东城"},{"all":220,"pid":18000,"quesId":18002,"quesName":"西城"},{"all":120,"pid":18000,"quesId":18003,"quesName":"朝阳"},{"all":120,"pid":18000,"quesId":18004,"quesName":"海淀"},{"all":100,"pid":18000,"quesId":18005,"quesName":"通州"}],"pid":1,"quesId":18000,"quesName":"北京"},{"all":840,"children":[{"all":200,"pid":19000,"quesId":19001,"quesName":"渝中"},{"all":120,"pid":19000,"quesId":19002,"quesName":"万州"},{"all":160,"pid":19000,"quesId":19003,"quesName":"陪陵"},{"all":120,"pid":19000,"quesId":19004,"quesName":"江北"},{"all":80,"pid":19000,"quesId":19005,"quesName":"沙坪坝"},{"all":120,"pid":19000,"quesId":19006,"quesName":"九龙坡"},{"all":40,"pid":19000,"quesId":19007,"quesName":"渝北"}],"pid":1,"quesId":19000,"quesName":"重庆"},{"all":1430,"children":[{"all":200,"pid":20000,"quesId":20001,"quesName":"福田"},{"all":220,"pid":20000,"quesId":20002,"quesName":"罗湖"},{"all":360,"pid":20000,"quesId":20003,"quesName":"南山"},{"all":210,"pid":20000,"quesId":20004,"quesName":"盐田"},{"all":120,"pid":20000,"quesId":20005,"quesName":"宝安"},{"all":120,"pid":20000,"quesId":20006,"quesName":"龙岗"},{"all":120,"pid":20000,"quesId":20007,"quesName":"龙华"},{"all":80,"pid":20000,"quesId":20008,"quesName":"坪山"}],"pid":1,"quesId":20000,"quesName":"深圳"},{"all":600,"children":[{"all":600,"pid":21000,"quesId":21001,"quesName":"新加坡"}],"pid":1,"quesId":21000,"quesName":"新加坡"},{"all":100,"children":[{"all":100,"pid":22000,"quesId":22001,"quesName":"东京"}],"pid":1,"quesId":22000,"quesName":"东京"},{"all":600,"children":[{"all":600,"pid":23000,"quesId":23001,"quesName":"莫斯科"}],"pid":1,"quesId":23000,"quesName":"莫斯科"},{"all":550,"children":[{"all":550,"pid":24000,"quesId":24001,"quesName":"梵蒂冈"}],"pid":1,"quesId":24000,"quesName":"梵蒂冈"},{"all":211,"children":[{"all":211,"pid":25000,"quesId":25001,"quesName":"纽约"}],"pid":1,"quesId":25000,"quesName":"纽约"},{"all":163,"children":[{"all":163,"pid":26000,"quesId":26001,"quesName":"尼日利亚"}],"pid":1,"quesId":26000,"quesName":"尼日利亚"}],"message":"请求成功","status":200}
// function getCateData() {
//   return cateData
// }
// const departData = {"data": [{"deptName": "南山","all":360,"done": 300},{"deptName": "东城区","all":240,"done": 200},{"deptName": "渝中","all":200,"done": 200},{"deptName": "黄埔","all":150,"done": 150},{"deptName": "新加坡","all":600,"done": 580},{"deptName": "莫斯科","all":600,"done": 600},{"deptName": "梵蒂冈","all":550,"done": 500},{"deptName": "成都","all":220,"done": 220},{"deptName": "纽约","all":211,"done":211},{"deptName": "罗湖","all":220,"done": 210}],"message":"请求成功","status":200}
// function getDepartTop() {
//   return departData
// }
// export { getCateData, getDepartTop }


// 返回随机个数
const cateData = {
  "data": [{
    "all": 484,
    "children": [{
      "all": 120,
      "pid": 10000,
      "quesId": 10001,
      "quesName": "武汉"
    }, {
      "all": 100,
      "pid": 10000,
      "quesId": 10002,
      "quesName": "鄂州"
    }, {
      "all": 90,
      "pid": 10000,
      "quesId": 10003,
      "quesName": "咸宁"
    }, {
      "all": 66,
      "pid": 10000,
      "quesId": 10004,
      "quesName": "黄冈"
    }, {
      "all": 88,
      "pid": 10000,
      "quesId": 10005,
      "quesName": "荆州"
    }],
    "pid": 1,
    "quesId": 10000,
    "quesName": "湖北"
  }, {
    "all": 450,
    "children": [{
      "all": 100,
      "pid": 11000,
      "quesId": 11001,
      "quesName": "广州"
    }, {
      "all": 200,
      "pid": 11000,
      "quesId": 11002,
      "quesName": "惠州"
    }, {
      "all": 70,
      "pid": 11000,
      "quesId": 11003,
      "quesName": "珠海"
    }, {
      "all": 80,
      "pid": 11000,
      "quesId": 11004,
      "quesName": "佛山"
    }],
    "pid": 1,
    "quesId": 11000,
    "quesName": "广东"
  }],
  "message": "请求成功",
  "status": 200
}
Mock.mock('/api/k', () => {
  return cateData
})

// 返回随机个数折线数据pie1和pie2用的接口
Mock.mock('/api/line', () => {
  return Mock.mock({
    // 'list|10': [{
    //   'id|+1': 1,
    //   'classroom|1': ['精品语文班', '精品作业A班', '英语班', '语文班'],
    //   'from|1': ['到店咨询', '微店', '壹家教', '学习服务平台'],
    //   'status|1': ['意识强烈', '预报名', '意向一般', '暂无意向'],
    // }],
    // 'list:10': [{
    //   'id|+1': 1,
    //   
    // }]
    'list|3': [{
      'id|+1': 1,
      'name|3': ['@cname'], //随机产生一个中文的姓名
      'time|3': ['@DATETIME("yyyy-MM-dd HH:mm:ss")'],
      // 'content': '@cparagraph',
      'num|2': ['@float(1, 300)']
    }],
  })
})

// 返回随机个数折线数据pie1和pie2用的接口
Mock.mock('/api/lineAdd', () => {
  return Mock.mock({
    'list|3': [{ //  list 代表数组名称  后面3代表个数
      'id|+1': 1,
      'name': ['@cname'], //随机产生一个中文的姓名
      'time': ['@DATETIME("yyyy-MM-dd HH:mm:ss")'],
      // 'content': '@cparagraph',
      'num|5': ['@float(1, 300)']
    }],
    'list2|3': [{
      'id|+1': 1,
      'name': ['@cname'], //随机产生一个中文的姓名
      'time': ['@DATETIME("yyyy-MM-dd HH:mm:ss")'],
      // 'content': '@cparagraph',
      'num|5': ['@float(1, 300)']
    }],
    'list3|3': [{
      'id|+1': 1,
      'name': ['@cname'], //随机产生一个中文的姓名
      'time': ['@DATETIME("yyyy-MM-dd HH:mm:ss")'],
      // 'content': '@cparagraph',
      'num|5': ['@float(1, 300)']
    }],
  })
})

3.使用页面组件,随便创建一个,配置路由,代码如下

<template>
  <div>页面</div>
</template>

<script>
import {getCase} from '../api/request'  // 路径要匹配对上!!!
export default {
  mounted(){
    this.getData();
  },
  methods:{
    getData(){        // 也可以用原生的直接写路径请求
      getCase({}).then(res => {
        console.log(res,'res~~~~');
      })
    }
  }
}
</script>

4.效果如下图

在这里插入图片描述

感觉文章好的话记得点个心心和关注,有错的地方麻烦指正一下,多谢!!!

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2022-03-10 22:22:38  更:2022-03-10 22:23:00 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 7:15:25-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码