1.先创建一个vue-cli demo
vue init webpack json_server







2.好的,cli文件我们已经建好了,接下来让我们装上 axios HTTP库
cnpm install axios --save

3.安装json server
cnpm intall json-server --save-dev

首先,创建一个db.json,放在根目录下就可以了,它用于存放接口调用时的数据
比如:
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}

然后在dev-server.js中添加代码:
注意:将这块代码放在var server = app.listen(port)之前就行,现在在浏览器中访问http://localhost:8081应该就能进到jsonserver页面中
const jsonServer = require('json-server')
const apiServer = jsonServer.create()
const apiRouter = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
apiServer.use(middlewares)
apiServer.use(apiRouter)
apiServer.listen(port+1, () => {
console.log('JSON Server is running')
})


浏览器中访问http://localhost:8081 出现下图情况说明你成功了。。

4.在文件main.js中添加 引入组件

5.在App.vue 中写你的代码
<template>
<div id="app">

<button @click="getPosts()">获取jsonserver中的数据</button>
<button @click="add()">添加一个商品</button>
<button @click="getItem(7)">查找某条商品数据</button>
<button @click="paginate()">分页</button>
<button @click="order()">排序</button>
<button @click="slice()">获取指定范围内的数据</button>
</div>
</template>
<script>
export default {
name: 'app',
components: {
},
methods: {
getPosts () {
this.$http.get('http://localhost:8081/cart')
.then(function (data){
console.log(data)
})
},
add () {
// 向数据库中添加数据
this.$http.post('http://localhost:8081/cart',{
title: "饼干!"
})
.then(function (data){
console.log(data)
})
},
getItem (id) {
// 查找某一条数据
this.$http.get('http://localhost:8081/cart?id=1&id=2')
.then(function (data){
console.log(data.data)
})
},
paginate () {
this.$http.get('http://localhost:8081/cart?_page=3&_limit=5')
.then(function (data){
console.log(data.data)
})
},
// 排序
order () {
this.$http.get('http://localhost:8081/cart?_sort=id&_order=desc')
.then(function (data){
console.log(data.data)
})
},
// 获取指定范围的数据
slice () {
this.$http.get('http://localhost:8081/cart?_start=22&_end=26')
.then(function (data){
console.log(data.data)
})
}
}
}
</script>

<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

结果:

最后:附上json-server 的API文档:点我直达
网友评论