Vue3中简单使用Mock.js方法实例分析

mock.js简介

-1

官方链接:Mock.js (mockjs.com)

前端开发人员用来模拟虚拟数据,拦截AJAX请求,方便模拟后端接口

安装

  1. npm install mockjs

使用

本文主要介绍在vue项目中使用mock.js,包括axIOS发送请求与请求简单封装

  1. 创建mock文件夹,新建index.js文件
    1. // 引入mockjs
    2. import Mock from “mockjs”;
    3. // 获取 mock.Random 对象
    4. const Random = Mock.Random;
    5. // 使用mockjs模拟数据
    6. let tableList = [
    7.      {
    8.      id: “5ffa80aD-9CF4-0C77-eBFC-f6612BfAcF4F”,
    9.      account: “admin”,
    10.      password: “123456”,
    11.      address: “36918166@qq.com”,
    12.      },
    13.      {
    14.      id: “4FcC922C-C72c-95c3-Ef92-FbFAc24cc831”,
    15.      account: “ebHoL6”,
    16.      password: “i320Hu74fbn2Gi”,
    17.      address: “48165263@qq.com”,
    18.      },
    19. ]
    20. // for (let i = 0; i < 20; i++) {
    21. // let newObject = {
    22. // id: Random.guid(), // 获取全局唯一标识符
    23. // account: /^[a-zA-Z0-9]{4,6}$/,
    24. // password: /^[a-zA-Z]\w{5,17}$/,
    25. // address: /[1-9]\d{7,10}@qq\.com/,
    26. // };
    27. // tableList.push(newObject);
    28. // }
    29. /** get请求
    30.      * 获取用户列表
    31.      */
    32. Mock.mock(“/api/mockGetList”, “get”, () => {
    33.      return {
    34.      code: “0”,
    35.      data: tableList,
    36.      };
    37. });
    38. /** post请求添加表格数据 */
    39. Mock.mock(“/api/add”, “post”, (params) => {
    40.      let newData = JSON.parse(params.body);
    41.      newData.id = Random.guid();
    42.      tableList.push(newData);
    43.      return {
    44.      code: “0”,
    45.      message: “success”,
    46.      data: tableList,
    47.      };
    48. });

    模拟数据可自己手动编写,也可由for循环自动生成,可以设置数量,字段(可以通过正则表达式限制输出格式)。最后可设定请求路径,请求方式以及返回内容,可根据自身需求进行更改。

  2. 创建api文件夹,新建http.js文件(请求封装)
    1. import axios from “axios”;
    2. import { ElLoading, ElMessage } from “element-plus”;
    3. let http = axios.create({
    4.      baseURL: “”,
    5.      timeout: 10000,
    6. });
    7. let loadingInstance;
    8. // 拦截器的添加
    9. http.interceptors.request.use(
    10.      (config) => {
    11.      loadingInstance = ElLoading.service(“加载中”);
    12.      return config;
    13.      },
    14.      (err) => {
    15.      loadingInstance?.close();
    16.      ElMessage.error(网络异常”);
    17.      return Promise.reject(err);
    18.      }
    19. );
    20. //响应拦截器
    21. http.interceptors.response.use(
    22.      (res) => {
    23.      loadingInstance?.close();
    24.      return res.data;
    25.      },
    26.      (err) => {
    27.      loadingInstance?.close();
    28.      ElMessage.error(“请求失败”);
    29.      return Promise.reject(err);
    30.      }
    31. );
    32. export default http;

    这部分主要是对请求进行封装

  3. 新建mockApi.js文件(接口封装)
    1. import http from “./http.js”;
    2. export default {
    3.      //用户列表
    4.      findAll() {
    5.      return http({
    6.          url: `/api/mockGetList`,
    7.          method: “get”,
    8.      });
    9.      },
    10.      //添加用户
    11.      addUser(user) {
    12. return http({
    13.          url: `/api/add`,
    14.          method: “post”,
    15.          data: user,
    16.      });
    17.      },
    18. }

    注意:url与提交方法要与mock中模拟请求保持一致

  4. 调用封装好的接口

导入模拟数据与接口文件,根据自己的路径进行修改

  1. import “../mock/index.js”;
  2. import mockApi from “../api/mockApi/mockApi.js”;

调用接口

  1. //页面数据请求
  2. let tableData = reactive([]);
  3. const getList = () => {
  4.      mockApi
  5.      .findAll()
  6.      .then((res) => {
  7.          console.log(res)
  8.          if (res.code === “0”){
  9.          tableData.push.apply(tableData, res.data);
  10.          }
  11.      })
  12.      .catch(function (error) {
  13.          console.log(error);
  14.      });
  15. };
  16. getList(); //直接调用请求方法
  17. //添加用户
  18. mockApi
  19.      .addUser(editUser)
  20.      .then((res) => {
  21.          console.log(res)
  22.      if (res.code === “0”) {
  23.          ElMessage({
  24.              message: “保存成功”,
  25.              type: “success”,
  26.              });
  27.          }
  28.      })
  29.      .catch(function (error) {
  30.          console.log(error);
  31. });

项目结构

-2

结构大体如上,mock中的Management.js就是文中说到的使用第一步,根据自身需要进行修改

PS:ApiFox中如今也集成了mock.js的功能,提供了postman类似的模拟发送请求功能之外,还提供了更多的web程序开发所需要的定制化功能!

ApiFox官网下载地址:https://apifox.com/

或本站下载地址:https://www.jb51.net/softs/737017.html

标签

发表评论