作为一个前端开发工程师,在后端还没有ready的时候,不可避免的要使用mock的数据。很多时候,我们并不想使用简单的静
态数据,而是希望自己起一个本地的mock-server来完全模拟请求以及请求回来的过程。json-server是一个很好的可以替
我们完成这一工作的工具。
1、安装
cnpm i json-server -g
2、新建数据文件(我建立的是一个api文件)
3、启动json-server
json-server api/city.json
因为我json文件里面有两个对象`
{
"list": [
{
"id": 1,
"title": "bim项目启动了",
"date": "2018-08-12",
"likes": 33,
"views": 124
},
{
"id": 2,
"title": "bim项目启动了",
"date": "2018-08-12",
"likes": 5554,
"views": 212
}
],
"comments": [
{
"id": 1,
"news_id": 1,
"data": [
{
"id": 1,
"content": "测试数据"
},
{
"id": 2,
"content": "测试数据"
}
]
},
{
"name": "pyl",
"id": 2
}
]
}
`所以就生成了2个接口。
看见就基本成功了,接下来就是调用接口了
methods: {
json_getdata(params) {
return axios({
method: "get",
url: "http://localhost:3000/list",
params:{}
})
},
async getdata(){
const {data} = await this.json_getdata()
console.log(data);
}
},
完成!!
post/patch等等查询只放代码 不放结果了,截图太费劲了,浪费时间~
post
json_postdata(data) {
return axios({
method: "post",
url: "http://localhost:3000/list",
data: {
title: "bim项目启动了",
date: new Date(),
},
});
},
async postdata() {
const { data } = await this.json_postdata();
console.log(data);
},
patch
json_patchdata(id) {
return axios({
method: "patch",
url: "http://localhost:3000/list/3",
data: {
title: "我叫南京黑马潘奕霖",
},
});
},
async patchdata() {
const { data } = await this.json_patchdata();
console.log(data);
},
delete懒得写了 也就那么回事
附上完整代码
<template>
<div class="home">
<button @click="getdata">getdata</button>
<button @click="postdata">post</button>
<button @click="patchdata">patch</button>
<button>delete</button>
</div>
</template>
<script>
// @ is an alias to /src
import axios from "axios";
export default {
name: "Home",
data() {
return {
// num: 123
};
},
methods: {
json_patchdata(id) {
return axios({
method: "patch",
url: "http://localhost:3000/list/3",
data: {
title: "我叫南京黑马潘10",
},
});
},
async patchdata() {
const { data } = await this.json_patchdata();
console.log(data);
},
json_getdata(params) {
return axios({
method: "get",
url: "http://localhost:3000/list",
params: {},
});
},
async getdata() {
const { data } = await this.json_getdata();
console.log(data);
},
json_postdata(data) {
return axios({
method: "post",
url: "http://localhost:3000/list",
data: {
title: "bim项目启动了",
date: new Date(),
},
});
},
async postdata() {
const { data } = await this.json_postdata();
console.log(data);
},
},
};
</script>