Vue+Mockjs模擬curd接口請求的示例詳解
在前后端分離的項目中常常會遇到當前端頁面開發(fā)完成
但是后端接口還沒好,暫不支持聯(lián)調的情況下,一般我們會用到mock數(shù)據(jù)
這邊簡單說一下最常見且經(jīng)常會遇到的curd接口模擬
注:這邊可以和后端先約定好接口路徑以及入?yún)⒎祬⒌淖侄危苊舛涡薷?/p>
1.安裝依賴,新建js文件,在文件中導入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) // 調用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) { // 關鍵在于id,其他入?yún)⒉欢噘樖觯窬謎d找到那條數(shù)據(jù)調用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導出后,在調用時就會執(zhí)行mock的接口
相關文章
詳解.vue文件中監(jiān)聽input輸入事件(oninput)
本篇文章主要介紹了詳解.vue文件中監(jiān)聽input輸入事件(oninput),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09vue webpack build資源相對路徑的問題及解決方法
這篇文章主要介紹了vue webpack build資源相對路徑的問題,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06Vue3源碼分析組件掛載創(chuàng)建虛擬節(jié)點
這篇文章主要為大家介紹了Vue3源碼分析組件掛載創(chuàng)建虛擬節(jié)點,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10