一、mock 1、簡介 mock是一個模擬數據生成器,旨在幫助前端獨立於後端進行開發,幫助編寫單元測試。其可模擬 Ajax 並返回模擬數據,使前端不用去調用後端的介面,方便測試。 2、vue直接使用mock step1:安裝mock step2:直接引入mock.js,並編寫mock介面(Mock. ...
一、mock
1、簡介
mock是一個模擬數據生成器,旨在幫助前端獨立於後端進行開發,幫助編寫單元測試。其可模擬 Ajax 並返回模擬數據,使前端不用去調用後端的介面,方便測試。
2、vue直接使用mock
step1:安裝mock
npm install mockjs
step2:直接引入mock.js,並編寫mock介面(Mock.mock)。
【mock.js】
//引入mock模塊
import Mock from 'mockjs';
Mock.mock('/login', { //輸出數據
'name': '@name', //隨機生成姓名
//還可以自定義其他數據
});
Mock.mock('/list', { //輸出數據
'name': '@name', //隨機生成姓名
'age|10-20': 10
//還可以自定義其他數據
});
step3:在需要的地方引入編寫後的介面js即可。
【App.vue】 <template> <div> <button @click="login">login</button> <button @click="list">list</button> </div> <!--App --> </template> <script> import mock from './mock.js' import axios from 'axios' export default { methods: { login() { axios.post("/login").then(response => { if (response.data) { console.log(response.data) alert(response.data.name) } }) }, list() { axios.post("/list").then(response => { if (response.data) { console.log(response.data) alert(response.data.name + ',' + response.data.age) } }) } } } </script> <style> </style>
step4:代碼與截圖
目錄結構。使用vue-cli創建項目(詳見https://www.cnblogs.com/l-y-h/p/11241503.html)。
完整代碼
【main.js】 import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app') 【mock.js】 //引入mock模塊 import Mock from 'mockjs'; Mock.mock('/login', { //輸出數據 'name': '@name', //隨機生成姓名 //還可以自定義其他數據 }); Mock.mock('/list', { //輸出數據 'name': '@name', //隨機生成姓名 'age|10-20': 10 //還可以自定義其他數據 }); 【App.vue】 <template> <div> <button @click="login">login</button> <button @click="list">list</button> </div> <!--App --> </template> <script> import mock from './mock.js' import axios from 'axios' export default { methods: { login() { axios.post("/login").then(response => { if (response.data) { console.log(response.data) alert(response.data.name) } }) }, list() { axios.post("/list").then(response => { if (response.data) { console.log(response.data) alert(response.data.name + ',' + response.data.age) } }) } } } </script> <style> </style>
運行截圖:
初始畫面
點擊login 按鈕(隨機產生一個人名)
點擊list按鈕(隨機產生一個人名和年齡)
3、Vue項目中使用webpack-api-mocker進行mock
step1:安裝webpack-api-mocker
npm i webpack-api-mocker --save-dev
step2:編寫 /mocker/index.js,用於定義mock介面
【/mocker/index.js】
// 使用 require 引入json文件,可以直接訪問數據
const appData = require('../data.json')
const proxy = {
'GET /api/login': {
success: appData.login.success,
message: appData.login.message
},
'GET /api/list': [{
id: 1,
username: 'kenny',
sex: 6
},
{
id: 2,
username: 'kenny',
sex: 6
}
],
'POST /api/post': (req, res) => {
res.send({
status: 'error',
code: 403
});
},
'DELETE /api/remove': (req, res) => {
res.send({
status: 'ok',
message: '刪除成功!'
});
}
}
module.exports = proxy
step3:修改 vue.config.js 配置文件(若不存在,在項目下新建即可)
【vue.config.js】
const path = require('path')
const apiMocker = require('webpack-api-mocker')
module.exports = {
devServer: {
before(app) {
// 註意,此處引用的是自定義的介面文件
apiMocker(app, path.resolve('./mocker/index.js'), {
proxy: {
'/repos/*': 'https://api.github.com/',
},
changeHost: true,
})
}
}
}
step4:隨便定義一組 json 數據(用於測試)。
{
"login": {
"success": "true",
"message": "登陸成功"
},
"fileList": {
"success":"true",
"list":[
{"fileId":"1","fileName":"a1.c","content":"content-test1"
},
{"fileId":"2","fileName":"a2.c","content":"content-test2"
},
{"fileId":"3","fileName":"a3.c","content":"content-test2"
},
{"fileId":"4","fileName":"a4.c","content":"content-test2"
},
{"fileId":"5","fileName":"a5.c","content":"content-test2"
},
{"fileId":"6","fileName":"a8.c","content":"content-test2"
},
{"fileId":"7","fileName":"a9.c","content":"content-test2"
}]
}
}
step5:完整代碼、截圖
文件目錄結構:
完整代碼
【main.js】 import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app') 【App.vue】 <template> <div> <button @click="login">login</button> <button @click="list">list</button> <button @click="post">post</button> <button @click="remove">remove</button> </div> <!--App --> </template> <script> import axios from 'axios' export default { methods: { login() { axios.get("/api/login").then(response => { if (response.data) { console.log(response.data) alert(response.data.success + ',' + response.data.message) } }) }, list() { axios.get("/api/list").then(response => { if (response.data) { console.log(response.data) let list1 = response.data[0].id + ',' + response.data[0].sex + ',' + response.data[0].username let list2 = response.data[1].id + ',' + response.data[1].sex + ',' + response.data[1].username alert(list1 + '\n' + list2) } }) }, post() { axios.post("/api/post").then(response => { if (response.data) { console.log(response.data) alert(response.data.status + ',' + response.data.code) } }) }, remove() { axios.delete("/api/remove").then(response => { if (response.data) { console.log(response.data) alert(response.data.status + ',' + response.data.message) } }) } } } </script> <style> </style> 【data.json】 { "login": { "success": "true", "message": "登錄成功" }, "fileList": { "success":"true", "list":[ {"fileId":"1","fileName":"a1.c","content":"content-test1" }, {"fileId":"2","fileName":"a2.c","content":"content-test2" }, {"fileId":"3","fileName":"a3.c","content":"content-test2" }, {"fileId":"4","fileName":"a4.c","content":"content-test2" }, {"fileId":"5","fileName":"a5.c","content":"content-test2" }, {"fileId":"6","fileName":"a8.c","content":"content-test2" }, {"fileId":"7","fileName":"a9.c","content":"content-test2" }] } } 【vue.config.js】 const path = require('path') const apiMocker = require('webpack-api-mocker') module.exports = { devServer: { before(app) { // path.resolve 引入mock apiMocker(app, path.resolve('./mocker/index.js'), { proxy: { '/repos/*': 'https://api.github.com/', }, changeHost: true }) } } } 【/mocker/index.js】 // 使用 require 引入json文件,可以直接訪問數據 const appData = require('../data.json') const proxy = { 'GET /api/login': { success: appData.login.success, message: appData.login.message }, 'GET /api/list': [{ id: 1, username: 'kenny', sex: 6 }, { id: 2, username: 'kenny', sex: 6 } ], 'POST /api/post': (req, res) => { res.send({ status: 'error', code: 403 }); }, 'DELETE /api/remove': (req, res) => { res.send({ status: 'ok', message: '刪除成功!' }); } } module.exports = proxy
運行截圖:
點擊 login 按鈕
點擊 list 按鈕
點擊 post 按鈕
點擊remove按鈕