目录
-
✎?如何使用json-server实战
-
➀ 前期准备
- 1 准备一下db.json
{
"getNewsList": [
{
"id": 1,
"title": "新闻条目1新闻条目1新闻条目1新闻条目1",
"url": "http://starcraft.com"
},
{
"id": 2,
"title": "新闻条目2新闻条目2新闻条目2新闻条目2",
"url": "http://warcraft.com"
},
{
"id": 3,
"title": "新闻条3新闻条3新闻条3",
"url": "http://overwatch.com"
},
{
"id": 4,
"title": "新闻条4广告发布",
"url": "http://hearstone.com"
}
],
"login": {
"username": "yudongdong",
"userId": 123123
},
"getPrice": {
"amount": 678
},
"createOrder": {
"orderId": "6djk979"
},
"getOrderList": {
"list": [
{
"orderId": "ddj123",
"product": "数据统计",
"version": "高级版",
"period": "1年",
"buyNum": 2,
"date": "2016-10-10",
"amount": "500元"
},
{
"orderId": "yuj583",
"product": "流量分析",
"version": "户外版",
"period": "3个月",
"buyNum": 1,
"date": "2016-5-2",
"amount": "2200元"
},
{
"orderId": "pmd201",
"product": "广告发布",
"version": "商铺版",
"period": "3年",
"buyNum": 12,
"date": "2016-8-3",
"amount": "7890元"
}
]
}
}
-
➁ 监控db.json
- 2.有db.json项目目录下执行命令
json-server --watch db.json
- 3 如下图所示
-
➂ 接口约定
- 4 将首页的newsList静态数据放到db.json中来模拟获取后端的数据,值得注意的是:
接口名是要和后端约定的!!!!
-
➃ GitHub引入配置
-
➊ GitHub官方例子
- 5 脚手架工具中已经提供了一个代理gitHub上面已经有了对应的例子:
-
➋ 项目配置内容
...(../config/index.js)
proxyTable: {
'/api':'http://localhost:8081/'
},...
......(../build/webpack.dev.conf.js)
// apiServer.use('/api', apiRouter)
apiServer.use(middlewares)
apiServer.use(apiRouter)
apiServer.listen(8081, () => {
console.log('JSON Server is running')
})
apiServer.use('/api', apiRouter)....
-
➌ 配置分析
- 6 分析和效果图
-
➍ 重启服务
- 7 配置完后重启服务
http://localhost:8081/ ---- json-server 服务
http://localhost:8081/getNewsList ---- 普通接口服务
http://localhost:8081/api/getNewsList -- 代理接口服务
-
✎?在项目中查看json-server的使用效果
-
json-server get请求
-
➀ ../src/pages/index.vue
<script>
export default {
created: function() {
this.$http.get('api/getNewsList').then(function(data) {
// 成功的回调
console.log(data)
}, function(error) {
// 失败的回调
console.log(error)
})
},
data() {
...
...
-
➁ 刷新页面http://localhost:8080/
-
➂this
利用es6的箭头函数,解决this值的问题,将其修改为函数整体代码环境下的this,而不是当前执行环境下的this:
export default {
created: function() {
this.$http.get('api/getNewsList')
// .then(function(res) {
.then((res) => {
// 成功的回调
this.newsList = res.data
console.log(this.newsList)
}, function(error) {
// 失败的回调
console.log(error)
})
},
data()
也可以用原来的方式整体替换:
-
➃ 建议使用箭头函数
<script>
export default {
created: function() {
this.$http.get('api/getNewsList')
.then((res) => {
// 成功的回调
this.newsList = res.data
console.log('数组',this.newsList)
}, (error) => {
// 失败的回调
console.log(error)
})
},
data() {
.....
-
➄ 接接口完毕,页面效果