vue-resource是Vue.js的一款插件,它可以通过XMLHttpRequest或JSONP发起请求并处理响应。$.ajax能做的事情,vue-resource插件一样可以做到,而且vue-reaource的API更为的简洁。另外,vue-resource还提供了非常有用的inteceptor功能,使用inteceptor可以在请求前和请求后附加一些行为,比如使用inteceptor在ajax请求时显示loading界面。
引入vue-resource.js和vue.js
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js">script>
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js">script>
// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
// 传统写法
this.$http.get('/someUrl', [options]).then(function(response){
// 响应成功回调
}, function(response){
// 响应错误回调
});
// Lambda写法
this.$http.get('/someUrl', [options]).then((response) => {
// 响应成功回调
}, (response) => {
// 响应错误回调
});
get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])
客户端请求方法 | 服务端处理方法 |
---|---|
this.$http.get(…) | Getxxx |
this.$http.post(…) | Postxxx |
this.$http.put(…) | Putxxx |
this.$http.delete(…) | Deletexxx |
发送请求时的options选项对象包含以下属性:
参数 | 类型 | 描述 |
---|---|---|
url | string |
请求的URL |
method | string |
请求的HTTP方法,例如:‘GET’, 'POST’或其他HTTP方法 |
body | Object , FormData string |
request body |
params | Object |
请求的URL参数对象 |
headers | Object |
request header |
timeout | number |
单位为毫秒的请求超时时间 (0 表示无超时时间) |
before | function(request) |
请求发送前的处理函数,类似于jQuery的beforeSend函数 |
progress | function(event) |
ProgressEvent回调处理函数 |
credentials | boolean |
表示跨域请求时是否需要使用凭证 |
emulateHTTP | boolean |
发送PUT, PATCH, DELETE请求时以HTTP POST的方式发送,并设置请求头的X-HTTP-Method-Override |
emulateJSON | boolean |
将request body以application/x-www-form-urlencoded content type发送 |
response对象包含以下属性:
方法 | 类型 | 描述 |
---|---|---|
text() | string |
以string形式返回response body |
json() | Object |
以JSON对象形式返回response body |
blob() | Blob |
以二进制形式返回response body |
属性 | 类型 | 描述 |
ok | boolean |
响应的HTTP状态码在200~299之间时,该属性为true |
status | number |
响应的HTTP状态码 |
statusText | string |
响应的状态文本 |
headers | Object |
响应头 |
创建一个springboot项目->引入相关的依赖->创建目录结构->配置数据库文件。
/*Table structure for table `book` */
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`count` int DEFAULT NULL,
`detail` varchar(50) DEFAULT NULL,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8;
/*Data for the table `book` */
insert into `book`(`id`,`name`,`count`,`detail`,`create_time`,`update_time`) values
(7,'Php',10,'编辑语言','2020-03-28 23:36:40','2020-03-31 22:29:44'),
(40,'Java',80,'面向对象程序设计','2020-11-26 20:31:00','2020-11-28 11:24:04'),
(48,'JavaWeb',10,'网页开发','2020-11-27 09:46:56','2020-11-27 10:05:47'),
(55,'数值分析',55,'计算方法基础','2020-11-27 10:47:46','2020-11-27 10:47:46'),
(57,'Python',36,'脚本语言','2020-11-27 10:48:32','2020-11-28 11:19:03');
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book implements Serializable {
private int id;
private String name;
private String detail;
private int count;
public Book(String name, String detail, int count) {
this.name = name;
this.detail = detail;
this.count = count;
}
}
@Mapper
@Repository
public interface BookDao extends BaseMapper<Book> {
//查询所有书籍
List<Book> queryAllBook();
//删除书籍
int deleteBook(int id);
//添加书籍
int addBook(Book book);
//修改书籍
int updateBook(Book book);
//根据id查询书籍
Book queryBookById(int id);
//根据书名查询书籍
List<Book> queryBookByName(String name);
}
service
public interface BookService {
//查询所有书籍
List<Book> queryAllBook();
//删除书籍
int deleteBook(int id);
//添加书籍
int addBook(Book book);
//修改书籍
int updateBook(Book book);
//根据id查询书籍
Book queryBookById(int id);
//根据书名查询书籍
List<Book> queryBookByName(String name);
}
实现类
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public List<Book> queryAllBook() {
return bookDao.selectList(null);
}
@Override
public int deleteBook(int id) {
QueryWrapper<Book> wrapper = new QueryWrapper<>();
wrapper.eq("id",id);
return bookDao.delete(wrapper);
}
@Override
public int addBook(Book book) {
return bookDao.insert(book);
}
@Override
public int updateBook(Book book) {
return bookDao.updateById(book);
}
@Override
public Book queryBookById(int id) {
return bookDao.selectById(id);
}
@Override
public List<Book> queryBookByName(String name) {
QueryWrapper<Book> wrapper = new QueryWrapper<>();
wrapper.eq("name",name);
return bookDao.selectList(wrapper);
}
}
@Controller
@ResponseBody
public class BookController {
@Autowired
private BookService bookService;
//查询所有书籍
@GetMapping("/list")
public List<Book> queryAllBook2(Model model){
List<Book> books = bookService.queryAllBook();
return books;
}
//删除书籍
@DeleteMapping("/delete/{id}")
public void deleteBook(@PathVariable("id") int id){
bookService.deleteBook(id);
}
//添加书籍
@PostMapping("/add/{name}/{detail}/{count}")
public void addBook(@PathVariable("name") String name,@PathVariable("detail")String detail,@PathVariable("count")int count){
bookService.addBook(new Book(name,detail,count));
}
//根据id查询书籍
@GetMapping("/query/{id}")
public Book queryBookById(@PathVariable("id") int id){
Book book = bookService.queryBookById(id);
return book;
}
//修改书籍
@PutMapping("/update/{id}/{name}/{detail}/{count}")
public void updateBook(@PathVariable("id") int id,@PathVariable("name") String name,@PathVariable("detail")String detail,@PathVariable("count")int count){
bookService.updateBook(new Book(id,name,detail,count));
}
//查找书籍
@GetMapping("/search/{name}")
public List<Book> queryBookByName(@PathVariable("name") String name){
List<Book> book = bookService.queryBookByName(name);
return book;
}
}
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>listtitle>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js">script>
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js">script>
head>
<body>
<div class="container" id="list" style="text-align: center">
<h3>书籍管理h3>
<div id="formBox" style="display:none;border: 1px solid #ffffff;padding: 30px 50px 0px 50px;text-align: center;margin: 10px auto;box-shadow: 0px 0px 10px 1px rgb(228, 224, 224)">
<form class="form-inline">
书名:<input class="form-control input-sm" type="text" v-model="name"><br><br>
描述:<input class="form-control input-sm" type="text" v-model="detail"><br><br>
数量:<input class="form-control input-sm" type="text" v-model="count"><br><br>
<input class="btn btn-success btn-sm" id="add2" type="button" value="添加" @click="post()">
<input class="btn btn-success btn-sm" id="update2" type="button" value="修改" @click="put(id)">
<input class="btn btn-info btn-sm" type="reset" value="重置">
form>
<span id="hide" class="glyphicon glyphicon-menu-up" aria-hidden="true" style="margin-top: 30px;font-size: 25px;color: #c6c5c5">span>
div>
<div>
<h4 style="float: left;cursor: pointer" @click="get()">书籍列表h4>
<button class="btn btn-primary btn-sm" style="float: right;margin-top: 6px" id="add">添加button>
<form class="form-inline" style="float: right;">
<input type="text" class="form-control input-sm" placeholder="Search for name" value="" id="search">
<span class="glyphicon glyphicon-search" aria-hidden="true" style="margin: 10px 30px 0px -25px" @click="getbookbyname()">span>
form>
div>
<table class="table table-striped" id="list2">
<tr style="font-weight:800;background-color: #c7c7c7">
<td>序号td>
<td>书名td>
<td>描述td>
<td>数量td>
<td>操作td>
tr>
<tr v-for="(book,i) in lists">
<td>{
{i+1}}td>
<td>{
{book.name}}td>
<td>{
{book.detail}}td>
<td>{
{book.count}}td>
<td>
<button class="btn btn-danger btn-xs" @click="del(book.id)">删除button>
<button class="btn btn-danger btn-xs" @click="getbookbyid(book.id)">修改button>
td>
tr>
table>
div>
body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js">script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js">script>
<script type="text/javascript">
var vm = new Vue({
el: '#list',
data: {
lists: [],
id: '',
name: '',
detail: '',
count: ''
},
// 页面加载时,初始化数据
created: function () {
this.$http.get('/list').then((response) => {
this.lists = response.data
}).catch(function (response) {
console.log(response)
})
},
// 增删查改方法
methods: {
// 查询所有书籍
get: function () {
vm.$http.get('/list').then((response) => {
this.lists = response.data
}).catch(function (response) {
console.log(response)
})
},
//根据id查询书籍
getbookbyid: function (id) {
$("#formBox").slideDown("slow");
$("#add2").hide()
$("#update2").show()
vm.$http.get('/query/' + id).then((response) => {
this.id = response.data.id
this.name = response.data.name
this.detail = response.data.detail
this.count = response.data.count
})
},
//根据书名查询书籍
getbookbyname: function () {
let bookname = $('#search').val();
vm.$http.get('/search/' + bookname).then((response) => {
this.lists = response.data
})
},
// 添加书籍
post: function () {
$("#formBox").slideUp("slow");
vm.$http.post('/add/' + vm.name + "/" + vm.detail + "/" + vm.count).then((response) => {
vm.get()
})
},
//删除书籍
del: function (id) {
let b = confirm("是否要删除?");
if (b){
vm.$http.delete('/delete/' + id).then((response) => {
vm.get()
})
}
},
//修改书籍
put: function (id) {
$("#formBox").slideUp("slow");
vm.$http.put('/update/' + id + "/" + vm.name + "/" + vm.detail + "/" + vm.count).then((response) => {
vm.get()
})
}
}
});
$('#add').click(function () {
$("#formBox").slideDown("slow");
$("#update2").hide()
$("#add2").show()
})
$('#hide').click(function () {
$("#formBox").slideUp("slow");
})
script>
html>