Vue-resource实现前后端分离实例

Vue-resource实现前后端分离实例

vue-resource介绍

简介

vue-resource是Vue.js的一款插件,它可以通过XMLHttpRequest或JSONP发起请求并处理响应。$.ajax能做的事情,vue-resource插件一样可以做到,而且vue-reaource的API更为的简洁。另外,vue-resource还提供了非常有用的inteceptor功能,使用inteceptor可以在请求前和请求后附加一些行为,比如使用inteceptor在ajax请求时显示loading界面。

vue-resource特点
  • 体积小
  • 支持主流浏览器
  • 支持PromiseAPI和URI Templates
  • 支持拦截器
使用

引入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) => {
	// 响应错误回调
});
支持的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])
客户端请求方法服务端处理方法
this.$http.get(…)Getxxx
this.$http.post(…)Postxxx
this.$http.put(…)Putxxx
this.$http.delete(…)Deletexxx
option对象

发送请求时的options选项对象包含以下属性:

参数类型描述
urlstring请求的URL
methodstring请求的HTTP方法,例如:‘GET’, 'POST’或其他HTTP方法
bodyObject, FormData stringrequest body
paramsObject请求的URL参数对象
headersObjectrequest header
timeoutnumber单位为毫秒的请求超时时间 (0 表示无超时时间)
beforefunction(request)请求发送前的处理函数,类似于jQuery的beforeSend函数
progressfunction(event)ProgressEvent回调处理函数
credentialsboolean表示跨域请求时是否需要使用凭证
emulateHTTPboolean发送PUT, PATCH, DELETE请求时以HTTP POST的方式发送,并设置请求头的X-HTTP-Method-Override
emulateJSONboolean将request body以application/x-www-form-urlencoded content type发送
response对象

response对象包含以下属性:

方法类型描述
text()string以string形式返回response body
json()Object以JSON对象形式返回response body
blob()Blob以二进制形式返回response body
属性类型描述
okboolean响应的HTTP状态码在200~299之间时,该属性为true
statusnumber响应的HTTP状态码
statusTextstring响应的状态文本
headersObject响应头

书籍管理项目实例

搭建坏境
  • springboot
  • mysql
  • mybatis-plus
具体创建项目步骤:

创建一个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');
创建实体类Book
@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;
    }
}
创建BookDao
@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和serviceImpl

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
@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;
    }
}
创建首页
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>list</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/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/jquery@1.12.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/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>
界面展示

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值