上手玩一下 json-server(一)了解篇
上手玩一下 json-server(二)操作数据篇——POST/PATCH/DELETE
举个例子:
// network/index.js
import Vue from 'vue';
import Axios from "axios";
import VueAxios from "vue-axios";
Vue.use(VueAxios, Axios);
Vue.axios.defaults.baseURL = 'http://localhost:3000';
Vue.axios.defaults.timeout = 5000;
function request() {
return Vue.axios;
}
export default request
// network/service/fruit.js
import request from "../index";
export function getFruits() {
return request().get('/fruit')
}
export function addFruit() {
return request().post('/fruit', {
"name": "apple",
"price": 5,
})
}
export function deleteFruit() {
return request().delete('/fruit/1')
}
export function updateFruit() {
return request().put('/fruit/2', {
"name": "pear",
"price": 6,
})
}
export function patchFruit() {
return request().patch('/fruit/3', {
"name": "sss"
})
}
// db.json
{
"fruit": []
}
// App.vue
<template>
<div id="app">
<button @click="c">create</button>
<button @click="r">retrieve</button>
<button @click="u">update</button>
<button @click="p">Partial update</button>
<button @click="d">delete</button>
</div>
</template>
<script>
import {addFruit, getFruits, updateFruit, patchFruit, deleteFruit} from "./network/service/fruit";
export default {
name: 'App',
methods: {
c() {
addFruit()
.then(value => console.log(value))
.catch(reason => console.log(reason))
},
r() {
getFruits()
.then(value => console.log(value))
.catch(reason => console.log(reason))
},
u() {
updateFruit()
.then(value => console.log(value))
.catch(reason => console.log(reason))
},
p() {
patchFruit()
.then(value => console.log(value))
.catch(reason => console.log(reason))
},
d() {
deleteFruit()
.then(value => console.log(value))
.catch(reason => console.log(reason))
}
},
}
</script>
<style>
</style>
网友评论