1.先創(chuàng)建一個vue-cli demo
vue init webpack json_server
image.png
image.png
image.png
image.png
image.png
image.png
image.png
2.好的统扳,cli文件我們已經(jīng)建好了,接下來讓我們裝上 axios HTTP庫
cnpm install axios --save
image.png
3.安裝json server
cnpm intall json-server --save-dev
image.png
首先,創(chuàng)建一個db.json逃沿,放在根目錄下就可以了透揣,它用于存放接口調(diào)用時的數(shù)據(jù)
比如:
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
image.png
然后在dev-server.js中添加代碼:
注意:將這塊代碼放在var server = app.listen(port)之前就行济炎,現(xiàn)在在瀏覽器中訪問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')
})
image.png
image.png
瀏覽器中訪問http://localhost:8081 出現(xiàn)下圖情況說明你成功了。淌实。
image.png
4.在文件main.js中添加 引入組件
image.png
5.在App.vue 中寫你的代碼
<template>
<div id="app">

<button @click="getPosts()">獲取jsonserver中的數(shù)據(jù)</button>
<button @click="add()">添加一個商品</button>
<button @click="getItem(7)">查找某條商品數(shù)據(jù)</button>
<button @click="paginate()">分頁</button>
<button @click="order()">排序</button>
<button @click="slice()">獲取指定范圍內(nèi)的數(shù)據(jù)</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 () {
// 向數(shù)據(jù)庫中添加數(shù)據(jù)
this.$http.post('http://localhost:8081/cart',{
title: "餅干冻辩!"
})
.then(function (data){
console.log(data)
})
},
getItem (id) {
// 查找某一條數(shù)據(jù)
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)
})
},
// 獲取指定范圍的數(shù)據(jù)
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>
image.png
結(jié)果:
josn_server.gif
最后:附上json-server 的API文檔:點我直達