json-server 可以用于模擬請(qǐng)求 ----Restful風(fēng)格
查詢 get params:{}
增加 post data:{}
刪除 delete
修改 put /patch data:{}
使用步驟
1-全局安裝 npm i json-server -g / yarn global add json-server 相當(dāng)于安裝了一個(gè)命令行工具
2-準(zhǔn)備json文件
{
"list": [
{
"name": "斑老師",
"flag": true,
"id": 6
},
{
"name": "貓咪老師",
"flag": true,
"id": 8
}
]
}
3-在當(dāng)前json文件下運(yùn)行 json-server data.json 開啟本地服務(wù)
開啟服務(wù)
4-看到上圖表示服務(wù)開啟成功 http://localhost:3000/list
增刪改查----axios
查詢以axios為例 請(qǐng)求方式為get
1-查詢?nèi)繑?shù)據(jù) 并且按照id進(jìn)行排序 排序方式為降序排序
axios({
method: "get",
url: "http://localhost:3000/list?_sort=id&_order=desc"
}).then(res => {
this.list = res.data;
}).catch(err => {
console.log(err);
})
2-查詢指定id的數(shù)據(jù) http://localhost:3000/list/6
axios({
method: "get",
url: "http://localhost:3000/list/6"
}).then(res => {
this.list = res.data;
}).catch(err => {
console.log(err);
})
3-增加數(shù)據(jù)post
axios({
method: "post",
url: "http://localhost:3000/list",
data: {
name: todoName,
flag: false
}
}).then(res => {
this.getData()
}).catch(err => {
console.log(err);
})
4-刪除指定id的數(shù)據(jù)
axios({
method: "delete",
url: `http://localhost:3000/list/${id}`,
}).then(res => {
this.getData();
}).catch(err => {
console.log(err);
})
url: `http://localhost:3000/list/${id}`, 這個(gè)位置用到了es6的模板字符串
5-修改數(shù)據(jù)
屏幕快照 2019-07-01 17.42.19.png
axios({
method: "patch",
url: `http://localhost:3000/list/${id}`,
data: {
flag
}
}).then(res => {
this.getData();
}).catch(err => {
console.log(err);
})
補(bǔ)充點(diǎn):put和patch的區(qū)別
put和patch都可以進(jìn)行修改操作
區(qū)別
put 方式如果沒有將所有屬性都寫完整 沒寫的屬性會(huì)丟失
patch方式?jīng)]修改的屬性不寫默認(rèn)為之前的值
舉例:{id:1,name:"zs",age:18}
修改age=20
put:{id:1,age:20}
patch:{id:1,name:"zs",age:20}