vue3+ts+mock实现增删改查json文件的示例代码

 更新时间:2025年07月23日 11:21:54   作者:战族狼魂  
本文主要介绍了vue3+ts+mock实现增删改查json文件的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1.代码结构图:

2.路由

import { createRouter, createWebHashHistory } from "vue-router";

import Home from "@/pages/home/index.vue";
import AppDetail from "@/pages/app-detail/index.vue";
import PageDetail from "@/pages/page-detail/index.vue";

const routes = [
  {
    path: `/`,
    component: Home,
  },
  {
    path: `/app/:id`,
    name: 'app',
    component: AppDetail,
  },

  {
    path: `/page/:id`,
    name: 'page',
    component: PageDetail,
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
});

export default router;

3.在api文件夹中创建index.ts文件

import { request } from "@/utils"

export const queryApp = () => request("/web_bp_api/app/list");
export const addApp = (newData: any) => request('/web_bp_api/app/add', newData);
export const updateApp = (id: number | string, updatedData: any) => request(`/web_bp_api/app/update`, { id, updatedData });
export const deleteApp = (id: number | string) => request(`/web_bp_api/app/delete`, { id });
export const queryPage = () => request("/web_bp_api/page/list");
export const addPage = (newPageData: any) => request('/web_bp_api/page/add', newPageData);
export const updatePage = (pageId: string | number, updatedPageData: any) => request(`/web_bp_api/page/update`, { pageId, updatedPageData });
export const deletePage = (pageId: string | number) => request(`/web_bp_api/page/delete`, { pageId });
export const queryModule = () => request("/web_bp_api/module/list");
export const addModule = (newModuleData: any) => request('/web_bp_api/module/add', newModuleData);
export const updateModule = (moduleId: string | number, updatedModuleData: any) => request(`/web_bp_api/module/update`, { moduleId, updatedModuleData });
export const deleteModule = (moduleId: string | number) => request(`/web_bp_api/module/delete`, { moduleId });

4.mock

import { responseSuccessFormat, responseErrorFormat } from "./utils";
import * as fs from 'fs';
import * as path from 'path';
// 加载初始数据
const appData = JSON.parse(fs.readFileSync(path.resolve('./mock/data/app.json'), 'utf8'));
const pageData = JSON.parse(fs.readFileSync(path.resolve('./mock/data/page.json'), 'utf8'));
const moduleData = JSON.parse(fs.readFileSync(path.resolve('./mock/data/module.json'), 'utf8'));

// 在内存中模拟数据库
const mockDatabase = {
  app: appData,
  page: pageData,
  module: moduleData
};
// 模拟的API路由处理函数
export default {
  // 列出应用(使用GET)
  "POST /web_bp_api/app/list": responseSuccessFormat(mockDatabase.app),
  // 新增应用(使用POST)
  "POST /web_bp_api/app/add": (req: any) => {
    console.log(req.body)
    const model = mockDatabase.app.reduce((prev: { id: number; }, curr: { id: number; }) => {
      return prev.id > curr.id ? prev : curr
    })
    console.log(model.id)
    const newData = req.body; // 假设请求体中包含新数据
    newData.id = parseInt(model.id) + 1;
    newData.createTime = new Date().toLocaleString();
    newData.updateTime = "";
    mockDatabase.app.push(newData); // 模拟添加到数组中
    fs.writeFileSync(path.resolve('./mock/data/app.json'), JSON.stringify(mockDatabase.app, null, 2), 'utf8');
    return responseSuccessFormat(newData); // 返回新添加的数据作为示例
  },
  // 删除应用(使用DELETE,需要ID)
  "POST /web_bp_api/app/delete": (req: any) => {
    console.log(req.body)
    const id = req.body.id;
    // 假设ID是索引(在真实应用中,您可能需要更复杂的逻辑来找到对象)
    const index = mockDatabase.app.findIndex((item: { id: number; }) => item.id === parseInt(id));
    if (index !== -1) {
      mockDatabase.app.splice(index, 1); // 从数组中删除
      fs.writeFileSync(path.resolve('./mock/data/app.json'), JSON.stringify(mockDatabase.app, null, 2), 'utf8');
      return responseSuccessFormat({ deletedId: id });
    } else {
      return { status: 404, message: '未找到指定ID的应用' };
    }
  },

  // 更新应用(使用PUT,需要ID)
  "POST /web_bp_api/app/update": (req: any) => {
    console.log(req.body)
    const id = req.body.id;
    const newData = req.body.updatedData;
    newData.updateTime = new Date().toLocaleString();
    const index = mockDatabase.app.findIndex((item: { id: number; }) => item.id === parseInt(id));
    if (index !== -1) {
      mockDatabase.app[index] = { ...mockDatabase.app[index], ...newData };
      // 现在,您可能需要将更新后的数据写回文件
      fs.writeFileSync(path.resolve('./mock/data/app.json'), JSON.stringify(mockDatabase.app, null, 2), 'utf8');
      return responseSuccessFormat(mockDatabase.app[index]);
    } else {
      return { status: 404, message: '未找到指定ID的应用' };
    }
  },
  "POST /web_bp_api/page/list": responseSuccessFormat(mockDatabase.page),
  "POST /web_bp_api/page/add": (req: any) => {
    const newData = req.body; // 假设请求体中包含新数据
    mockDatabase.page.push(newData); // 模拟添加到数组中
    // 现在,您可能需要将更新后的数据写回文件
    fs.writeFileSync(path.resolve('./mock/data/page.json'), JSON.stringify(mockDatabase.page, null, 2), 'utf8');
    return responseSuccessFormat(newData); // 返回新添加的数据作为示例
  },
  "POST /web_bp_api/page/delete": (req: any) => {
    const { id } = req.params;
    // 假设ID是索引(在真实应用中,您可能需要更复杂的逻辑来找到对象)
    const index = mockDatabase.page.findIndex((item: { id: number; }) => item.id === parseInt(id));
    if (index !== -1) {
      mockDatabase.page.splice(index, 1); // 从数组中删除
      return responseSuccessFormat({ deletedId: id });
    } else {
      return { status: 404, message: '未找到指定ID的应用' };
    }
  },
  "POST /web_bp_api/page/update": (req: any) => {
    const { id } = req.params;
    const newData = req.body;
    const index = mockDatabase.page.findIndex((item: { id: number; }) => item.id === parseInt(id));
    if (index !== -1) {
      mockDatabase.page[index] = { ...mockDatabase.page[index], ...newData };
      return responseSuccessFormat(mockDatabase.page[index]);
    } else {
      return { status: 404, message: '未找到指定ID的应用' };
    }
  },
  "POST /web_bp_api/module/list": responseSuccessFormat(mockDatabase.module),
  "POST /web_bp_api/module/add": (req: any) => {
    const newData = req.body; // 假设请求体中包含新数据
    mockDatabase.module.push(newData); // 模拟添加到数组中
    return responseSuccessFormat(newData); // 返回新添加的数据作为示例
  },
  "POST /web_bp_api/module/delete": (req: any) => {
    const { id } = req.params;
    const index = mockDatabase.module.findIndex((item: { id: number; }) => item.id === parseInt(id));
    if (index !== -1) {
      mockDatabase.module.splice(index, 1);
      return responseSuccessFormat({ deletedId: id });
    } else {
      return { status: 404, message: '未找到指定ID的应用' };
    }
  },
  "POST /web_bp_api/module/update": (req: any) => {
    const { id } = req.params;
    const newData = req.body;
    const index = mockDatabase.module.findIndex((item: { id: number; }) => item.id === parseInt(id));
    if (index !== -1) {
      mockDatabase.module[index] = { ...mockDatabase.module[index], ...newData };
      return responseSuccessFormat(mockDatabase.module[index]);
    } else {
      return { status: 404, message: '未找到指定ID的模块' };
    }
  },
};

app.json文件

[
  {
    "id": 2,
    "name": "租车平台56",
    "description": "租车业务管理后台",
    "spmid": "a456",
    "createTime": "2023-05-09",
    "updateTime": "2024/8/25 00:32:43"
  },
  {
    "id": 3,
    "name": "埋点管理",
    "description": "埋点申请、埋点数据报表查看",
    "spmid": "a789",
    "createTime": "2023-05-09",
    "updateTime": "2023-05-09"
  }
]

到此这篇关于vue3+ts+mock实现增删改查json文件的示例代码的文章就介绍到这了,更多相关vue3 mock增删改查json内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Vue报错Component name"Home"should always be multi问题

    Vue报错Component name"Home"should always be mult

    这篇文章主要介绍了Vue报错Component name"Home"should always be multi问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09
  • vue table直接定位到指定元素的操作代码

    vue table直接定位到指定元素的操作代码

    最近遇到这样的需求点击某一个节点,弹窗,直接定位到点击的节点,高亮并显示数据,下面小编给大家带来了vue table直接定位到指定元素的操作代码,需要的朋友可以参考下
    2022-11-11
  • VUE之关于store状态管理核心解析

    VUE之关于store状态管理核心解析

    这篇文章主要介绍了VUE之关于store状态管理核心解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • vue的ElementUI form表单如何给label属性字符串中添加空白占位符

    vue的ElementUI form表单如何给label属性字符串中添加空白占位符

    这篇文章主要介绍了vue的ElementUI form表单如何给label属性字符串中添加空白占位符问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • vue3+vant4封装日期时间组件方式(年月日时分秒)

    vue3+vant4封装日期时间组件方式(年月日时分秒)

    这篇文章主要介绍了vue3+vant4封装日期时间组件方式(年月日时分秒),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • 学习vue.js条件渲染

    学习vue.js条件渲染

    这篇文章主要和大家一起学习vue.js条件渲染,代码注释详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-12-12
  • vant Cascader级联选择实现可以选择任意一层级

    vant Cascader级联选择实现可以选择任意一层级

    这篇文章主要介绍了vant Cascader级联选择实现可以选择任意一层级方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-07-07
  • 使用Vue+ElementUI动态生成面包屑导航教程

    使用Vue+ElementUI动态生成面包屑导航教程

    Vue和ElementUI都是非常流行的前端开发框架,它们可以让我们更加便捷地开发前端应用,下面这篇文章主要给大家介绍了关于使用Vue+ElementUI动态生成面包屑导航的相关资料,需要的朋友可以参考下
    2023-05-05
  • Cookbook组件形式:优化 Vue 组件的运行时性能

    Cookbook组件形式:优化 Vue 组件的运行时性能

    本文仿照Vue Cookbook 组织形式,对优化 Vue 组件的运行时性能进行阐述。通过基本的示例代码给大家讲解,需要的朋友参考下
    2018-11-11
  • 让Vue响应Map或Set的变化操作

    让Vue响应Map或Set的变化操作

    这篇文章主要介绍了让Vue响应Map或Set的变化操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-11-11

最新评论