vue3+ts+mock實(shí)現(xiàn)增刪改查json文件的示例代碼
1.代碼結(jié)構(gòu)圖:


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文件夾中創(chuàng)建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';
// 加載初始數(shù)據(jù)
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'));
// 在內(nèi)存中模擬數(shù)據(jù)庫
const mockDatabase = {
app: appData,
page: pageData,
module: moduleData
};
// 模擬的API路由處理函數(shù)
export default {
// 列出應(yīng)用(使用GET)
"POST /web_bp_api/app/list": responseSuccessFormat(mockDatabase.app),
// 新增應(yīng)用(使用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; // 假設(shè)請求體中包含新數(shù)據(jù)
newData.id = parseInt(model.id) + 1;
newData.createTime = new Date().toLocaleString();
newData.updateTime = "";
mockDatabase.app.push(newData); // 模擬添加到數(shù)組中
fs.writeFileSync(path.resolve('./mock/data/app.json'), JSON.stringify(mockDatabase.app, null, 2), 'utf8');
return responseSuccessFormat(newData); // 返回新添加的數(shù)據(jù)作為示例
},
// 刪除應(yīng)用(使用DELETE,需要ID)
"POST /web_bp_api/app/delete": (req: any) => {
console.log(req.body)
const id = req.body.id;
// 假設(shè)ID是索引(在真實(shí)應(yīng)用中,您可能需要更復(fù)雜的邏輯來找到對象)
const index = mockDatabase.app.findIndex((item: { id: number; }) => item.id === parseInt(id));
if (index !== -1) {
mockDatabase.app.splice(index, 1); // 從數(shù)組中刪除
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的應(yīng)用' };
}
},
// 更新應(yīng)用(使用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 };
// 現(xiàn)在,您可能需要將更新后的數(shù)據(jù)寫回文件
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的應(yīng)用' };
}
},
"POST /web_bp_api/page/list": responseSuccessFormat(mockDatabase.page),
"POST /web_bp_api/page/add": (req: any) => {
const newData = req.body; // 假設(shè)請求體中包含新數(shù)據(jù)
mockDatabase.page.push(newData); // 模擬添加到數(shù)組中
// 現(xiàn)在,您可能需要將更新后的數(shù)據(jù)寫回文件
fs.writeFileSync(path.resolve('./mock/data/page.json'), JSON.stringify(mockDatabase.page, null, 2), 'utf8');
return responseSuccessFormat(newData); // 返回新添加的數(shù)據(jù)作為示例
},
"POST /web_bp_api/page/delete": (req: any) => {
const { id } = req.params;
// 假設(shè)ID是索引(在真實(shí)應(yīng)用中,您可能需要更復(fù)雜的邏輯來找到對象)
const index = mockDatabase.page.findIndex((item: { id: number; }) => item.id === parseInt(id));
if (index !== -1) {
mockDatabase.page.splice(index, 1); // 從數(shù)組中刪除
return responseSuccessFormat({ deletedId: id });
} else {
return { status: 404, message: '未找到指定ID的應(yīng)用' };
}
},
"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的應(yīng)用' };
}
},
"POST /web_bp_api/module/list": responseSuccessFormat(mockDatabase.module),
"POST /web_bp_api/module/add": (req: any) => {
const newData = req.body; // 假設(shè)請求體中包含新數(shù)據(jù)
mockDatabase.module.push(newData); // 模擬添加到數(shù)組中
return responseSuccessFormat(newData); // 返回新添加的數(shù)據(jù)作為示例
},
"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的應(yīng)用' };
}
},
"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": "租車業(yè)務(wù)管理后臺",
"spmid": "a456",
"createTime": "2023-05-09",
"updateTime": "2024/8/25 00:32:43"
},
{
"id": 3,
"name": "埋點(diǎn)管理",
"description": "埋點(diǎn)申請、埋點(diǎn)數(shù)據(jù)報(bào)表查看",
"spmid": "a789",
"createTime": "2023-05-09",
"updateTime": "2023-05-09"
}
]到此這篇關(guān)于vue3+ts+mock實(shí)現(xiàn)增刪改查json文件的示例代碼的文章就介紹到這了,更多相關(guān)vue3 mock增刪改查json內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue報(bào)錯(cuò)Component?name"Home"should?always?be?mult
這篇文章主要介紹了Vue報(bào)錯(cuò)Component?name"Home"should?always?be?multi問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
VUE之關(guān)于store狀態(tài)管理核心解析
這篇文章主要介紹了VUE之關(guān)于store狀態(tài)管理核心解析,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
vue的ElementUI form表單如何給label屬性字符串中添加空白占位符
這篇文章主要介紹了vue的ElementUI form表單如何給label屬性字符串中添加空白占位符問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
vue3+vant4封裝日期時(shí)間組件方式(年月日時(shí)分秒)
這篇文章主要介紹了vue3+vant4封裝日期時(shí)間組件方式(年月日時(shí)分秒),具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
vant?Cascader級聯(lián)選擇實(shí)現(xiàn)可以選擇任意一層級
這篇文章主要介紹了vant?Cascader級聯(lián)選擇實(shí)現(xiàn)可以選擇任意一層級方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
使用Vue+ElementUI動態(tài)生成面包屑導(dǎo)航教程
Vue和ElementUI都是非常流行的前端開發(fā)框架,它們可以讓我們更加便捷地開發(fā)前端應(yīng)用,下面這篇文章主要給大家介紹了關(guān)于使用Vue+ElementUI動態(tài)生成面包屑導(dǎo)航的相關(guān)資料,需要的朋友可以參考下2023-05-05
Cookbook組件形式:優(yōu)化 Vue 組件的運(yùn)行時(shí)性能
本文仿照Vue Cookbook 組織形式,對優(yōu)化 Vue 組件的運(yùn)行時(shí)性能進(jìn)行闡述。通過基本的示例代碼給大家講解,需要的朋友參考下2018-11-11

