Vue 項(xiàng)目本地 Mock 數(shù)據(jù)
1. 前言
本小節(jié)我們將帶大家學(xué)習(xí)如何在 Vue-Cli3 初始化的項(xiàng)目中創(chuàng)建 Mock 數(shù)據(jù)。
2. 簡(jiǎn)介
在日常開發(fā)中,接口的聯(lián)調(diào)是非常普遍的。然而,有些時(shí)候接口并不會(huì)及時(shí)提供,這時(shí)候就需要我們自己 Mock 數(shù)據(jù)來(lái)模擬接口的實(shí)現(xiàn)。
3. 創(chuàng)建 Mock 數(shù)據(jù)
首先,我們?cè)陧?xiàng)目的根路徑下創(chuàng)建 vue.config.js 文件,并在文件中寫如下配置:
module.exports = {
devServer: {
before(app) {
app.get("/goods/list", (req, res) => {
res.json({
data: [
{name: 'Vue 基礎(chǔ)教程'},
{name: 'React 基礎(chǔ)教程'}
]
});
});
}
}
};
我們通過(guò) axios 來(lái)獲取接口數(shù)據(jù)。首先需要安裝 axios:
npm install axios --save
在組件中使用 axios 獲取 Mock 數(shù)據(jù):
<script>
import axios from "axios";
export default {
name: "Home",
created() {
axios.get("/goods/list").then(res => {
console.log(res);
});
},
components: {}
};
</script>
有時(shí)候,我們需要寫很多的 Mock 數(shù)據(jù),把所有的數(shù)據(jù)都寫在 vue.config.js 文件中顯然是不合適的,這會(huì)使得文件變得非常大,并且難以維護(hù)。我們可以在項(xiàng)目中創(chuàng)建 Mock 文件夾,把所有數(shù)據(jù)放在 Mock 文件夾中維護(hù)。
我們?cè)?Mock 文件夾中創(chuàng)建 list.json
[
{"name": "Vue 基礎(chǔ)學(xué)習(xí)"},
{"name": "React 基礎(chǔ)學(xué)習(xí)"}
]
然后,在 vue.config.js 文件中加載數(shù)據(jù):
const list = require("./mock/list.json");
module.exports = {
devServer: {
before(app) {
app.get("/goods/list", (req, res) => {
res.json({
data: list
});
});
}
}
};
4. 小結(jié)
本節(jié)我們帶大家學(xué)習(xí)了如何在項(xiàng)目中使用 Mock 數(shù)據(jù)。