Vue 項目本地 Mock 數(shù)據(jù)
1. 前言
本小節(jié)我們將帶大家學(xué)習(xí)如何在 Vue-Cli3 初始化的項目中創(chuàng)建 Mock 數(shù)據(jù)。
2. 簡介
在日常開發(fā)中,接口的聯(lián)調(diào)是非常普遍的。然而,有些時候接口并不會及時提供,這時候就需要我們自己 Mock 數(shù)據(jù)來模擬接口的實現(xiàn)。
3. 創(chuàng)建 Mock 數(shù)據(jù)
首先,我們在項目的根路徑下創(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ǔ)教程'}
]
});
});
}
}
};
我們通過 axios 來獲取接口數(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>
有時候,我們需要寫很多的 Mock 數(shù)據(jù),把所有的數(shù)據(jù)都寫在 vue.config.js 文件中顯然是不合適的,這會使得文件變得非常大,并且難以維護。我們可以在項目中創(chuàng)建 Mock 文件夾,把所有數(shù)據(jù)放在 Mock 文件夾中維護。
我們在 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í)了如何在項目中使用 Mock 數(shù)據(jù)。