Vue中如何使用mock模擬數(shù)據(jù)
Vue使用mock模擬數(shù)據(jù)
開發(fā)階段,為了提高效率,需要提前Mock減少代碼冗余,靈活插拔減少溝通,減少接口聯(lián)調(diào)時間
1.編輯器安裝JSON5擴(kuò)展,(采用json5格式來讓json格式可以存在注釋)
2.新建mock文件夾 /userInfo.json5 文件 mock數(shù)據(jù)

3.在mock文件夾下,新建 index.js 引入剛剛mock的數(shù)據(jù)
const fs = require('fs');
const path = require('path');
const Mock = require('mockjs');//mockjs 導(dǎo)入依賴模塊
const JSON5 = require('json5');
//讀取json文件
function getJsonFile(filePath) {
//讀取指定json文件
let json = fs.readFileSync(path.resolve(__dirname,filePath), 'utf-8');
//解析并返回
return JSON5.parse(json);
}
//返回一個函數(shù)
module.exports = function(app){
//監(jiān)聽http請求
app.get('/user/userinfo', function (rep, res) {
//每次響應(yīng)請求時讀取mock data的json文件
//getJsonFile方法定義了如何讀取json文件并解析成數(shù)據(jù)對象
let json = getJsonFile('./userInfo.json5'); // mock數(shù)據(jù)
//將json傳入 Mock.mock 方法中,生成的數(shù)據(jù)返回給瀏覽器
res.json(Mock.mock(json));
});
app.post('/...mock的url',(req,res)=>{
let json = getJsonFile('./...mock的json5數(shù)據(jù)');
})
}4.vue.config.js中添加配置
module.exports = {
devServer: {
before: require('./mock/index.js')//引入mock/index.js
}
}5..vue文件下 發(fā)送ajax請求測試數(shù)據(jù)
import axios from 'axios'
export default {
mounted() {
axios.get('/user/userinfo')
.then(res => {
console.log(res)
})
.catch(err => {
console.error(err);
})
}
} 5.擴(kuò)充:移除MOCK
.env.development 文件中
MOCK=false
完善mock\index.js
module.exports = function(app){
if(process.env.MOCK == 'true'){
//監(jiān)聽http請求
app.get('/user/userinfo', function (rep, res) {
//每次響應(yīng)請求時讀取mock data的json文件
//getJsonFile方法定義了如何讀取json文件并解析成數(shù)據(jù)對象
let json = getJsonFile('./userInfo.json5');
//將json傳入 Mock.mock 方法中,生成的數(shù)據(jù)返回給瀏覽器
res.json(Mock.mock(json));
});
}
} Vue使用mock數(shù)據(jù)的幾種方式
以下講解基于vuecli3.0創(chuàng)建的項(xiàng)目
首先我們來說一說vue/cli 3.0 與 2.0 的一些不同:
- 3.0 移除了 static 文件目錄,新增了 public 目錄,這個目錄下的靜態(tài)資源不會經(jīng)過 webpack 的處理,會被直接拷貝,所以我們能夠直接訪問到該目錄下的資源,靜態(tài)數(shù)據(jù)(如json數(shù)據(jù)、圖片等)需要存放在這里。
- 3.0 移除了 config、build 等配置目錄,如果需要進(jìn)行相關(guān)配置我們需要在根目錄下創(chuàng)建 vue.config.js 進(jìn)行配置即可。
方式一:借助mockjs插件實(shí)現(xiàn)本地mock數(shù)據(jù)
1.安裝插件:npm i mockjs -D;
2.在src目錄下創(chuàng)建一個mock文件夾,在mock文件夾下創(chuàng)建一個index.js和一個json文件夾(用于存放項(xiàng)目需要的模擬數(shù)據(jù)),如下圖所示:

3.mock目錄下的index.js示例如下:
const Mock = require('mockjs');
//格式: Mock.mock( url, post/get , 返回的數(shù)據(jù));
Mock.mock('/index/foodlist', 'get', require('./json/foodlist.json'));
Mock.mock('/index/foodlist2', 'post', require('./json/foodlist2.json'));4.json文件夾下的json數(shù)據(jù)示例如下:
{
"code": 200,
"list": [
{
"imgSrc": "https://timgsa.baidu.com/timg?C2880.jpg%3Fmode%3Ddownload",
"name": "老弄堂1",
"term": "起送¥15 免配送費(fèi)"
},
{
"imgSrc": "https://timgsa.baidu.com/timg?2C2880.jpg%3Fmode%3Ddownload",
"name": "老弄堂2",
"term": "起送¥15 免配送費(fèi)"
}
]
}5.在main.js入口文件中引入mock數(shù)據(jù),不需要時,則注釋掉。
import Vue from 'vue';
import App from './App';
import router from './router';
require('./mock'); //引入mock數(shù)據(jù),關(guān)閉則注釋該行
Vue.config.productionTip = false;
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
});6.最后,在vue模板中使用即可
axios.get('/user/userInfo')
.then(function(res){
console.log(res);
})
.catch(function(err){
console.log(err);
});方式二:在public文件夾放mock數(shù)據(jù)(無需使用mockjs插件)
1.在public文件夾下創(chuàng)建一個mock文件夾,在mock文件夾里創(chuàng)建項(xiàng)目需要的json文件,目錄結(jié)構(gòu)如下:

2.在vue.config.js里進(jìn)行路徑配置,如下:

3.最后,在vue模板中使用即可
// 模擬請求本地mock數(shù)據(jù)(不基于插件)
this.$http.get('/api/foods.json').then(function(res){
let list = res.data.list;
console.log(list);
that.businessList = res.data.list;
})注:但是本方式貌似只能使用get請求方式,不支持post等其它方式,具體還需再研究下。
方式三:前端本地啟動一個nodejs服務(wù)
vue項(xiàng)目向nodejs服務(wù)請求mock數(shù)據(jù)
1.創(chuàng)建一個node項(xiàng)目(為了方便,本例直接在vue項(xiàng)目根目錄創(chuàng)建,當(dāng)然也可以是其它任何地方)

2.serve.js示例如下:
const http = require('http');
// url模塊用于處理與解析 前端傳給后臺的URL,適用于get請求(不適用于post請求),詳情參見文檔
const urlLib = require('url');
http.createServer(function(req, res){
let urlObj = urlLib.parse(req.url, true); // 注意:這里的第二個參數(shù)一定要設(shè)置為:true, query才能解析為對象形式,可以更加方便地獲取key:value
let url = urlObj.pathname;
let get = urlObj.query;
console.log(url);
// 模擬的mock數(shù)據(jù)
let data = {
"code": 200,
"list": [
{
"imgSrc": "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1126716551,3134048915&fm=26&gp=0.jpg",
"name": "老弄堂1",
"term": "起送¥15 免配送費(fèi)"
},
{
"imgSrc": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1582134004436&di=eee2d024a136e950daa694f56ea78a2d&imgtype=0&src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F16%2F12%2F05%2F56db465e153a5d808b54501846e88dca.jpg",
"name": "老弄堂2",
"term": "起送¥15 免配送費(fèi)"
}
]
}
// console.log(get.user);
if(url === "/food") { // 美食列表接口
res.write(JSON.stringify(data));
}
res.end();
}).listen(9000); 啟動node服務(wù):node serve
3.配置vue.config.js的proxy,解決跨域

注意:這里配置的端口號不要和node的端口一樣,否則會報端口號被占用
3.最后,在vue模板中使用即可
// 模擬請求本地node服務(wù)
this.$http.get('/api/food').then(function(res){
let list = res.data.list;
console.log(list);
that.businessList = res.data.list;
})總結(jié):以上介紹了三種使用mock數(shù)據(jù)的方式,方便前端開發(fā)在本地開發(fā)環(huán)境下開發(fā)項(xiàng)目,使前后端分離,加快了開發(fā)效率,個人建議使用方式一(使用方便、靈活)。
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue局部組件數(shù)據(jù)共享Vue.observable()的使用
隨著組件的細(xì)化,就會遇到多組件狀態(tài)共享的情況,今天我們介紹的是 vue.js 2.6 新增加的 Observable API ,通過使用這個 api 我們可以應(yīng)對一些簡單的跨組件數(shù)據(jù)狀態(tài)共享的情況,感興趣的可以了解一下2021-06-06
Vue3中Element Plus Table(表格)點(diǎn)擊獲取對應(yīng)id方式
這篇文章主要介紹了Vue3中Element Plus Table(表格)點(diǎn)擊獲取對應(yīng)id方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
基于elementUI使用v-model實(shí)現(xiàn)經(jīng)緯度輸入的vue組件
這篇文章主要介紹了基于elementUI使用v-model實(shí)現(xiàn)經(jīng)緯度輸入的vue組件,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05
將vue項(xiàng)目打包成電腦端應(yīng)用.exe的完整步驟
最近接了個小活,其中甲方要求把vue項(xiàng)目打包成exe安裝在windows上,其中有也會出現(xiàn)一些小問題和優(yōu)化,特此記錄,這篇文章主要給大家介紹了關(guān)于將vue項(xiàng)目打包成電腦端應(yīng)用.exe的完整步驟,需要的朋友可以參考下2023-10-10
Vue 數(shù)值改變頁面沒有刷新的問題解決(數(shù)據(jù)改變視圖不更新的問題)
這篇文章主要介紹了Vue 數(shù)值改變頁面沒有刷新的問題解決(數(shù)據(jù)改變視圖不更新的問題),本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09

