這幾天在寫自己的博客。。。然後後臺接口什麼的沒來得及寫。。。然後就想了下用mock去虛擬一個接口。
json-server
JSON Server 是一個創建僞RESTful服務器的工具,具體使用方法可以看官方文檔,這裏直接講在vue-cli 中的用法。
配置流程
全局安裝 $ npm install -g json-server
項目目錄下創建 mock 文件夾
mock 文件夾下添加 db.json 文件,內容如下
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
- package.json 添加命令
"mock": "json-server --watch mock/db.json"
啓動mock服務
- 命令行 $ npm run mock
命令行結果如圖:
- 瀏覽器輸入localhost:3000
- 瀏覽器輸入localhost:3000/posts
db.json 進階版 db.js
- 新建db.js
module.exports = function() {
var tree = require('./tree.json');
return {
tree
}
}
- 新建tree.json (這個文件爲模擬接口數據)
{
"mate" : {
"columns" : [
{
"label":"排序",
"name" :"sort",
"span":12
}
],
"rows": [
{
"id" : 1,
"label": "一級 1",
"sort" : 1,
"children": [{
"id" : 11,
"label": "二級 1-1",
"sort" : 1,
"status":1
}],
"status":1,
"num" : false
},
{
"id" : 2,
"label": "一級 2",
"sort" : 2,
"children": [{
"id" : 21,
"label": "二級 2-1",
"sort" : 1,
"status":1,
"num" : true
}, {
"id" : 22,
"label": "二級 2-2",
"sort" : 2,
"status":0,
"num" : true
}],
"status":1,
"num" : true
},
{
"id" : 3,
"label": "一級 3",
"sort" : 3,
"children": [{
"id" : 31,
"label": "二級 3-1",
"sort" : 1,
"status":0,
"num" : false
}, {
"id" : 32,
"label": "二級 3-2",
"sort" : 2,
"status":1,
"num" : true
}],
"status":1,
"num" : true
}
],
"btns" :[
{
"action" : "add",
"url" : "/form.txt",
"label" : "增加頂級欄目",
"type" : "success",
"isApi" : false,
"useId" : -1,
"isSelector" : false
}
],
"actions":[
{
"action" :"add",
"url" : "/form.txt",
"label" : "增加",
"type" : "success",
"isApi" : false,
"useid" : 0
},
{
"action" :"edit",
"url" : "/form.txt",
"label" : "修改",
"type" : "primary",
"isApi" : false,
"useid" : 0
},
{
"action" :"disable",
"label" : ["禁用導航","啓用導航"],
"urls" : ["/form1.txt","/form2.txt"],
"type" : ["warning","success"],
"isApi" : true,
"useid" : 0,
"switch" : true,
"switchKey": "status"
},
{
"action" :"delete",
"confirm" : {
"msg" : "確定刪除選中數據?"
},
"label" : "刪除",
"url" : "/form.txt",
"type" : "danger",
"isApi" : true,
"useid" : 0,
"canDisable" : true,
"disableKey" : "num"
}
]
},
"title" : "樹狀表格中心",
"currentView" : "KTreer"
}
package.json 命令
"mock": "json-server --watch mock/db.js"
啓動服務 localhost:3000/tree
注意:
- json-server的訪問方式get和post大有不同。。。坑
進階用法請看→json-server-api