ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 8、案例:图书管理 需求 ![](https://img.kancloud.cn/5d/2b/5d2b47851dcc8e1233c8358758632987_940x448.png) # 1.图书列表 ● 实现静态列表效果 ● 基于数据实现模板效果 ● 处里每行的操作按钮 # 数据循环渲染 ![](https://img.kancloud.cn/00/5c/005cc5d284f621f86835d33901842cf1_712x274.png) @click.prevent 阻止a标签默认跳转 # 2.添加图书 ● 实现表单的静态效果 ● 添加图书表单域数据绑定 ● 添加按钮事件绑定 ● 实现添加业务逻辑 ![](https://img.kancloud.cn/f8/0d/f80d52972ea6a5ec6d764e9b79e4c771_668x291.png) # 3.修改图书 ● 修改信息填充到表单 ● 修改后重新提交表单 ● 重用添加和修改的方法 disabled="true" 禁止输入 ![](https://img.kancloud.cn/b3/cd/b3cd60cc1331ae2da9bcf26d4dbe500a_672x494.png) ~~~ 添加功能优化 handle: function(){ if(this.flag) { //编辑操作 //就是根据当前的ID去更新数组中对应的数据 this.books.some( (item) => { if(item. id ==this.id) { item.name =this.name; //完成更新操作之后,需要终止循环 return true ; }); this. flag = false; }else{ //添加 //添加图书 var book={}; book.id = this.id; book.name=this.name; book.date= ' '; this.books.push(book) ; //清空表单 this.id = ' '; this.name=' ' ; } this.id = ' '; this.name = ' ' ; } ~~~ ~~~ toEdit: function(id){ //禁止修改ID this.flag=true ; console.log(id) //根据ID查询出要编辑的数据 var book = this books.filter( function(item){ return item.id == id ; }); console. log(book) //把获取到的信息填充到表单 this.id = book[0].id; this.name = book[0].name ; } ~~~ # 4.删除图书 ● 删除按钮绑定事件处理方法 ● 实现删除业务逻辑 ![](https://img.kancloud.cn/09/33/0933c5ff63e31085b4988891fb7afc3d_668x287.png) ~~~ deleteBook: function(id){ //删除图书 //根据id从数组中查找元素的索引 // var index = this . books . f indIndex ( function( item) { // return item.id == id ; // }); //根据索引删除数组元素 // this. books.splice(index, 1); // //方法二:通过filter方法进行删除 this . books. fi lter( function( item){ return item. id != id; }); } ~~~ # 常用特性应用场景 ## ● 过滤器(格式化日期) ## ● 自定义指令(获取表单焦点) ## ● 计算属性(统计图书数量) ## ● 侦听器(验证图书存在性) ## ● 生命周期(图书数据处理) ~~~ computed: { total: function( ){ //计算图书的总数 return this . books . length; }}, watch: { name: function(val) { //验证图书名称是否已经存在 var flag = this . books . some ( function( item){ return item. name == val; }); if(flag) { //图书名称存在 this . submitFlag = true ; }else{ //图书名称不存在 this . submitFlag = false ; } } }, mounted: function( ){ //该生命周期钩子函数被触发的时候,模板已经可以使用 //一般此时用于获取后台数据,然后把数据填充到模板 vardata=[{ id:1, name: '三 国演义", date: 2525609975000 },{ id: 2, name : 水浒传', date: 2525609975000 id:3, name : 红楼梦” date: 2525609975000 },{ id: 4, name : .西游记', date: 2525609975000 }]; this. books = data; } }); ~~~