Vue+Mockjs模擬curd接口請求的示例詳解
在前后端分離的項目中常常會遇到當(dāng)前端頁面開發(fā)完成
但是后端接口還沒好,暫不支持聯(lián)調(diào)的情況下,一般我們會用到mock數(shù)據(jù)
這邊簡單說一下最常見且經(jīng)常會遇到的curd接口模擬
注:這邊可以和后端先約定好接口路徑以及入?yún)⒎祬⒌淖侄?,避免二次修?/p>
1.安裝依賴,新建js文件,在文件中導(dǎo)入mock.js,模擬列表數(shù)據(jù)
yarn add mockjs
const Mock = require("mockjs")
const list = []
const length = 18
for (let i = 0; i < length; i++) {
list.push(
Mock.mock({
id: '@id',
account: '@first',
name: '@name',
email: '@email',
mobile: '@phone',
sex: '@integer(0,1)',
type: "@integer(100,101)",
status: "@integer(0,1)",
})
)
}2.查詢列表接口模擬
{
url: "/user/getPageList",
type: "post",
response: config => {
// 拿到入?yún)?
const {
name,
account,
status,
type,
pageNum,
pageSize,
} = config.body;
// 做一些查詢條件的處理
const mockData = list.filter(item => {
if (name && item.name.indexOf(name) < 0) return false
if (account && item.account.toString() !== account) return false
if (status && item.status.toString() !== status) return false
if (type && item.type.toString() !== type) return false
return true
})
// 模擬分頁
const pageList = mockData.slice((pageNum - 1) * pageSize, pageNum * pageSize)
// 返回數(shù)據(jù)
return {
resultCode: "1",
messageCode: null,
message: null,
data: {
list: pageList,
total: mockData.length
}
};
}
},3.刪除功能接口模擬
{
url: "/user/removeRow",
type: "post",
response: config => {
const {
id
} = config.body
// 根據(jù)id找到需要刪除的元素索引
const index = list.findIndex(item => item.id === id)
// 調(diào)用splice刪除
list.splice(index, 1)
return {
resultCode: "1",
messageCode: null,
message: null,
data: 'success'
}
}
},4.保存及編輯接口模擬
{
url: "/user/saveForm",
type: "post",
response: config => {
const {
id
} = config.body
if (id) {
// 關(guān)鍵在于id,其他入?yún)⒉欢噘樖?,格局id找到那條數(shù)據(jù)調(diào)用splice替換
const index = list.findIndex(item => item.id === id)
list.splice(index, 1, config.body)
} else {
// 如果id不存在則在列表添加一條數(shù)據(jù)
list.unshift(
Mock.mock({
id: '@id',
...config.body
})
)
}
return {
resultCode: "1",
messageCode: null,
message: null,
data: 'success'
}
}
},如上便是簡易的curd接口模擬,具體mock-server.js的配置可去網(wǎng)上查閱
所有接口使用module.exports導(dǎo)出后,在調(diào)用時就會執(zhí)行mock的接口
相關(guān)文章
解決vue單頁面應(yīng)用中動態(tài)修改title問題
這篇文章主要介紹了解決vue單頁面應(yīng)用中動態(tài)修改title問題,本文通過示例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06
基于Vue3+UniApp在單個頁面實現(xiàn)固定TabBar的多種方式
tabBar 是移動端應(yīng)用常見的頁面效果,用于實現(xiàn)多頁面的快速切換,本文給大家介紹了如何基于Vue3+UniApp在單個頁面實現(xiàn)固定TabBar的多種方式,需要的朋友可以參考下2025-03-03
vue項目之?dāng)?shù)量占比進(jìn)度條實現(xiàn)方式
這篇文章主要介紹了vue項目之?dāng)?shù)量占比進(jìn)度條實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
在vscode中統(tǒng)一vue編碼風(fēng)格的方法
本篇文章主要介紹了在vscode中統(tǒng)一vue編碼風(fēng)格的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
vue-cli 自定義指令directive 添加驗證滑塊示例
本篇文章主要介紹了vue-cli 自定義指令directive 添加驗證滑塊示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
vue 自動檢測手機(jī)端響應(yīng)式布局的五種實現(xiàn)
本文主要介紹了vue自動檢測手機(jī)端響應(yīng)式布局,可以通過結(jié)合 CSS 媒體查詢、Vue 的動態(tài)數(shù)據(jù)綁定、適當(dāng)?shù)牡谌綆?、PostCSS 插件以及正確的視口設(shè)置實現(xiàn),感興趣的可以了解一下2024-07-07

