詳解vue-cli 本地開發(fā)mock數(shù)據(jù)使用方法
vue-cli 中可以通過配置 proxyTable 解決開發(fā)環(huán)境的跨域問題,具體可以參考這篇文章:Vue-cli proxyTable 解決開發(fā)環(huán)境的跨域問題
如果后端接口尚未開發(fā)完成,前端開發(fā)一般使用mock數(shù)據(jù)。
mock方法有多種多樣,這里給出兩種:
方法一: 使用express搭建靜態(tài)服務(wù)
mock數(shù)據(jù)寫在json文件中,proxyTable 里將接口代理到具體mock數(shù)據(jù)json文件上。
具體方法:
創(chuàng)建 mock 文件夾
build/dev-server.js 中添加如下代碼

npm run dev 啟動后,可以通過 http://localhost:8080/mock/db.json 訪問數(shù)據(jù),proxyTable對應(yīng)設(shè)置代理即可(代理設(shè)置方法與解決跨域方法相似)

方法二 使用 JSON Server 搭建 Mock 服務(wù)器
JSON Server 是一個創(chuàng)建偽RESTful服務(wù)器的工具,具體使用方法可以看官方文檔,這里直接講在vue-cli 中的用法。
配置流程
全局安裝 $ npm install -g json-server
項目目錄下創(chuàng)建 mock 文件夾
mock 文件夾下添加 db.json 文件,內(nèi)容如下
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
package.json 添加命令
"mock": "json-server --watch mock/db.json", "mockdev": "npm run mock & npm run dev"

啟動 mock 服務(wù)器
$ npm run mock 命令 運行 mock server
訪問 http://localhost:3000/
發(fā)現(xiàn) db.json 下第一級 json 對象被解析成為可訪問路徑

GET請求具體路徑 如:http://localhost:3000/posts 可獲取數(shù)據(jù)

faker.js 批量生成偽數(shù)據(jù)
如果需要大量的偽數(shù)據(jù),手動構(gòu)造比較費時費力,可以使用faker.js 批量生成。faker.js 的具體使用參見官方文檔,這里做一個示例。
$ cnpm install faker -G 全局安裝 faker
mock 目錄下創(chuàng)建 faker-data.js,內(nèi)容如下
module.exports = function () {
var faker = require("faker");
faker.locale = "zh_CN";
var _ = require("lodash");
return {
people: _.times(100, function (n) {
return {
id: n,
name: faker.name.findName(),
avatar: faker.internet.avatar()
}
}),
address: _.times(100, function (n) {
return {
id: faker.random.uuid(),
city: faker.address.city(),
county: faker.address.county()
}
})
}
}
$ json-server mock/faker-data.js 在 json server 中使用 faker
請求 http://localhost:3000/address 可以獲取到隨機(jī)生成的100組偽數(shù)據(jù)

添加中間件
json server 使用 RESTful 架構(gòu),GET請求可以獲取數(shù)據(jù),POST 請求則是添加數(shù)據(jù)。
在開發(fā)過程中,有時候想直接模擬獲取POST請求返回結(jié)果,可以添加 express 中間件 將POST請求轉(zhuǎn)為GET請求。
mock 目錄下創(chuàng)建 post-to-get.js,內(nèi)容如下
module.exports = function (req, res, next) {
req.method = "GET";
next();
}
啟動命令添加運行中間件 --m mock/post-to-get.js
"mock": "json-server --watch mock/db.json --m mock/post-to-get.js",
重新啟動服務(wù),POST請求就被轉(zhuǎn)換為GET請求了

其他需求也可以通過添加不同的中間件實現(xiàn)。
代理設(shè)置
在 config/index.js 的 proxyTable 將請求映射到 http://localhost:3000

代碼中添加請求以測試效果

$ npm run mockdev 啟動帶mock 數(shù)據(jù)的本地服務(wù)
結(jié)果如下:

整體代碼:https://github.com/carrotz/vue-cli-mock
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue使用數(shù)組splice方法失效,且總刪除最后一項的問題及解決
這篇文章主要介紹了vue使用數(shù)組splice方法失效,且總刪除最后一項的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

