在项目中创建一个 mock 文件夹,里面的文件为 xxx.json
类型
// swipe.json
{
"status": 0,
"message": [
{
"id": 1,
"img": "http://www.33lc.com/article/UploadPic/2012-8/20128161021784940.jpg"
},
{
"id": 2,
"img": "http://pic1.win4000.com/wallpaper/c/537d6d7bbfe70.jpg"
},
{
"id": 3,
"img": "http://www.wallcoo.com/human/Yokohama_Night_View/wallpapers/1440x900/yokohama_img_79009.jpg"
},
{
"id": 4,
"img": "http://attach.bbs.miui.com/forum/201304/01/143356iyko7yja01z1zocc.jpg"
},
{
"id": 5,
"img": "http://www.wallcoo.com/human/Yokohama_Night_View/wallpapers/1440x900/yokohama_img_25017.jpg"
},
{
"id": 6,
"img": "http://img.pconline.com.cn/images/upload/upc/tx/softbbs/1011/22/c0/5947950_1290393874324_1024x1024soft.jpg"
}
]
}
在项目根目录创建 vue.config.js
文件,输入下面内容,配置 mock
const swipeData = require("./mock/swipe.json");
const lalaData = require("./mock/lala.json");
module.exports = {
//...
devServer: {
port: 8080,
before(app) {
app.get("/api/index", (req, res) => {
res.json(swipeData);
});
app.get("/api/main", (req, res) => {
res.json(lalaData);
});
}
}
};
在需要使用的 文件中 调用 mock,
需要先安装 axios
安装方法 npm install axios --save
<script>
import axios from "axios";
export default {
name: "home",
data() {
return {
// ...
};
},
components: {
// ...
},
mounted() {
this.getHomeData();
},
methods: {
getHomeData() {
axios.get("/api/index").then(res => {
console.log(res)
}
});
}
}
};
</script>