Vue3中简单使用Mock.js方法实例分析
mock.js简介
官方链接:Mock.js (mockjs.com)
前端开发人员用来模拟虚拟数据,拦截AJAX请求,方便模拟后端接口
安装
- npm install mockjs
使用
本文主要介绍在vue项目中使用mock.js,包括axIOS发送请求与请求简单封装
- 创建mock文件夹,新建index.js文件
- // 引入mockjs
- import Mock from “mockjs”;
- // 获取 mock.Random 对象
- const Random = Mock.Random;
- // 使用mockjs模拟数据
- let tableList = [
- {
- id: “5ffa80aD-9CF4-0C77-eBFC-f6612BfAcF4F”,
- account: “admin”,
- password: “123456”,
- address: “36918166@qq.com”,
- },
- {
- id: “4FcC922C-C72c-95c3-Ef92-FbFAc24cc831”,
- account: “ebHoL6”,
- password: “i320Hu74fbn2Gi”,
- address: “48165263@qq.com”,
- },
- ]
- // for (let i = 0; i < 20; i++) {
- // let newObject = {
- // id: Random.guid(), // 获取全局唯一标识符
- // account: /^[a-zA-Z0-9]{4,6}$/,
- // password: /^[a-zA-Z]\w{5,17}$/,
- // address: /[1-9]\d{7,10}@qq\.com/,
- // };
- // tableList.push(newObject);
- // }
- /** get请求
- * 获取用户列表
- */
- Mock.mock(“/api/mockGetList”, “get”, () => {
- return {
- code: “0”,
- data: tableList,
- };
- });
- /** post请求添加表格数据 */
- Mock.mock(“/api/add”, “post”, (params) => {
- let newData = JSON.parse(params.body);
- newData.id = Random.guid();
- tableList.push(newData);
- return {
- code: “0”,
- message: “success”,
- data: tableList,
- };
- });
模拟数据可自己手动编写,也可由for循环自动生成,可以设置数量,字段(可以通过正则表达式限制输出格式)。最后可设定请求路径,请求方式以及返回内容,可根据自身需求进行更改。
- 创建api文件夹,新建http.js文件(请求封装)
- import axios from “axios”;
- import { ElLoading, ElMessage } from “element-plus”;
- let http = axios.create({
- baseURL: “”,
- timeout: 10000,
- });
- let loadingInstance;
- // 拦截器的添加
- http.interceptors.request.use(
- (config) => {
- loadingInstance = ElLoading.service(“加载中”);
- return config;
- },
- (err) => {
- loadingInstance?.close();
- ElMessage.error(“网络异常”);
- return Promise.reject(err);
- }
- );
- //响应拦截器
- http.interceptors.response.use(
- (res) => {
- loadingInstance?.close();
- return res.data;
- },
- (err) => {
- loadingInstance?.close();
- ElMessage.error(“请求失败”);
- return Promise.reject(err);
- }
- );
- export default http;
这部分主要是对请求进行封装
- 新建mockApi.js文件(接口封装)
- import http from “./http.js”;
- export default {
- //用户列表
- findAll() {
- return http({
- url: `/api/mockGetList`,
- method: “get”,
- });
- },
- //添加用户
- addUser(user) {
- return http({
- url: `/api/add`,
- method: “post”,
- data: user,
- });
- },
- }
注意:url与提交方法要与mock中模拟请求保持一致
- 调用封装好的接口
导入模拟数据与接口文件,根据自己的路径进行修改
- import “../mock/index.js”;
- import mockApi from “../api/mockApi/mockApi.js”;
调用接口
- //页面数据请求
- let tableData = reactive([]);
- const getList = () => {
- mockApi
- .findAll()
- .then((res) => {
- console.log(res)
- if (res.code === “0”){
- tableData.push.apply(tableData, res.data);
- }
- })
- .catch(function (error) {
- console.log(error);
- });
- };
- getList(); //直接调用请求方法
- //添加用户
- mockApi
- .addUser(editUser)
- .then((res) => {
- console.log(res)
- if (res.code === “0”) {
- ElMessage({
- message: “保存成功”,
- type: “success”,
- });
- }
- })
- .catch(function (error) {
- console.log(error);
- });
项目结构
结构大体如上,mock中的Management.js就是文中说到的使用第一步,根据自身需要进行修改
PS:ApiFox中如今也集成了mock.js的功能,提供了postman类似的模拟发送请求功能之外,还提供了更多的web程序开发所需要的定制化功能!
ApiFox官网下载地址:https://apifox.com/
或本站下载地址:https://www.jb51.net/softs/737017.html
发表评论