第二十三篇:自定义事件(比如删除)
好家伙,贼绕,贼复杂
1.以下就是用自定义事件实现删除的功能
模块去上删除vue中的数据,需要参数传递和事件分发
2.前端可以控制模块,也可以控制vue.
上代码(实现组件删除的功能)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--view层,模板-->
//视图层 <div id="vue"> <todo> <todo-title slot="todo-title" :title="title_text"></todo-title> <!--<todo-items slot="todo-items" v-for="(item,index) in todoItems" v-bind:item="item"></todo-items>--> <!--如下为简写--> <todo-items slot="todo-items" v-for="(item,index) in todoItems" :item_p="item" :index_p="index" v-on:remove="removeItems(index)" :key="index"></todo-items> </todo >//通过v-bind绑定下面的组件 //自定义事件绑定vue实例中的事件,秒啊卧槽,v-on后的就是自定义事件,其中(index)从for循环中拿到 </div>
<!--1.导入Vue.js--> <script src="../js/vue.js"></script> <script type="text/javascript"> Vue.component('todo',{ template:'<div>\ <slot name="todo-title"></slot>\ <ul>\ <slot name="todo-items"></slot>\ </ul>\ </div>' });
Vue.component('todo-title',{ props:['title'], template:'<div>{{title}}</div>' });
//这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来! Vue.component("todo-items",{ //组件只能绑定自己的方法 props:["item_p","index_p"],//接受index把数据拿过来 //这里我绑定我自己的方法 template:"<li>{{index_p+1}},{{item_p}} <button @click='remove_methods'>删除</button></li>", methods:{ //关键来了,组件是不能删vue中的数据的,这里必须要通过前端 remove_methods:function (index) { //this.$emit 自定义事件分发, this.$emit('remove',index); } //"自定义事件名",传参数把index传给它,执行该方法删除该下标下当前元素
} }); var vm = new Vue({ el:"#vue", data:{ title_text:"秦老师系列课程", todoItems:['test1','test2','test3'] //普普通通的数据 }, methods:{ removeItems:function(index){ console.log("删除了"+this.todoItems[index]+"OK"); //控制台显示操作 this.todoItems.splice(index,1); //万能方法splice,这里用于删除 } } }); </script> </body> </html>
搞懂了,秒啊秒啊
3.组件---->前端----->vue对象
秒啊
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具