安装resource
$ npm install vue-resource
这个服务可以应用Vue.http或者在vue的实例中this.$http.
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
http中提供的方法
get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])
resource(url, [params], [actions], [options])
restful风格
get: {method: 'GET'},
save: {method: 'POST'},
query: {method: 'GET'},
update: {method: 'PUT'},
remove: {method: 'DELETE'},
delete: {method: 'DELETE'}
<div id="app">
<table class="table table-bordered">
<tr>
<td>书名</td>
<td>书的信息</td>
<td colspan="2">操作</td>
</tr>
<tr v-for="book in books">
<td>{{book.name}}</td>
<td>{{book.price}}</td>
<td><button class="btn btn-danger" @click="del(book)">删除</button></td>
<td><button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg" @click="update(book)">修改按钮</button></td>
</tr>
</table>
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="form-group ">
<label class="control-label">书的名字</label>
<input type="text" class="form-control" v-model="book.name">
</div>
<div class="form-group">
<label class="control-label">书的价格</label>
<input type="text" class="form-control" v-model="book.price">
</div>
<button class="btn" @click="sure()">修改</button>
</div>
</div>
</div>
</div>
var vm = new Vue({
el:'#app',
data:{
book:{
price:'',
name:'',
},
books:[]
},
ready(){
this.resource = this.$resource('/books{/id}');
this.resource.get().then((data)=>{
this.$set('books',data.json());
})
},
methods:{
del: function (book) {
this.resource.delete({id:book.id}).then(data=>{
this.$set('books',data.json());
});
}
,update: function (book) {
this.$set('book',book);
},
sure: function () {
this.resource.update({id:this.book.id},{book:this.book}).then(data=>{
this.$set('books',data.json());
$('.modal').modal('toggle');
});
}
}
})
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
console.log(path.resolve('lib'));
var books = [{
id:1,
name:'nodejs',
price:20
},{
id:2,
name:'vue',
price:10
},{
id:3,
name:'react',
price:30
}];
app.use(express.static(path.resolve('lib')));
app.get('/', function (req,res) {
res.sendFile('./1.html',{root:__dirname})
});
app.get('/books', function (req,res) {
res.contentType('application/json');
res.send(books)
});
app.delete('/books/:id', function (req,res) {
books = books.filter(function (item) {
return req.params.id != item.id;
});
res.send(books)
});
app.put('/books/:id', function (req,res) {
books = books.map(function (books) {
if(books.id == req.params.id){
var book = req.body.book;
books = book;
}
return books;
});
res.send(books);
});
app.listen(8080);