淺談vue專案用到的mock資料介面的兩種方式
阿新 • • 發佈:2020-11-18
1.使用devServer.before進行資料mock
//通過配置devServer.before選項,設定url訪問路徑及response響應資料,進行mock資料。 const { data } = require('./data.json') // 引入json資料物件 //vue.config.js配置檔案中進行Vue CLI的配置 module.exports = { //... devServer: { before: function(app, server) { app.get('/api/data', function(req, res) { res.json({ data: data, errno: 0 }); }); } } };
import axios from 'axios' const ERRNO = 0 //通過函式柯力化,接收url作為引數,以返回新的函式接收額外的引數作為axios配置項 function get (url) { return function (params) { return axios.get(url, { params }).then((res) => { const { errno, data } = res.data if (errno === ERRNO) { return data } }).catch((e) => { }) } } const getData = get('api/data') getSeller().then(res => { console.log(res) })
2.使用Mock.js進行資料mock
使用Mock.mock(),根據資料模板生成模擬資料。
import Mock from 'mockjs' import data from './bookHome' //匯入存放模擬json資料的js檔案 Mock.mock(/\/api\/data/, 'get', home) //表示需要攔截的 URL,可以是 URL 字串或 URL 正則。 //表示需要攔截的 Ajax 請求型別。例如 GET、POST、PUT、DELETE 等。 //表示資料模板,可以是物件或字串。例如 { 'data|1-10':[{}] }、'@EMAIL'。
/* axios獲取mock資料 */ import axios from 'axios' export function getData() { return axios({ method: 'get', url: `${process.env.VUE_APP_BOOK_URL}/api/data` //通過環境指定的預設地址設定介面url,方便後續呼叫 }) } //介面方法返回promise物件,最終獲取mock資料 getData().then(response => { if (response && response.status === 200) { const data = response.data console.log(data) } })
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援碼農教程。