vue自定义事件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=<device-width>, initial-scale=1.0"> <script crossorigin="anonymous" integrity="sha512-BKbSR+cfyxLdMAsE0naLReFSLg8/pjbgfxHh/k/kUC82Hy7r6HtR5hLhobaln2gcTvzkyyehrdREdjpsQwy2Jw==" src="https://lib.baomitu.com/vue/2.6.12/vue.min.js"></script> <title>Document</title> </head> <body> <!-- view --> <div id="app"> <one> <two slot="first" :name="username"></two> <three slot="second" :age="a" :index="index" v-for="(a,index) in allages" v-on:removesingle="removeage(index)"></three> </one> </div> <!-- viewmodel --> <script> //one 组件 Vue.component("one",{ template: '<div>\ <slot name="first"></slot>\ <ul>\ <slot name="second"></slot>\ </ul>\ </div>' }); //two 组件 Vue.component("two",{ props: ['name'], template: '<div>{{name}}</div>' }) //three 组件 Vue.component("three",{ props: ['age','index'], template: '<li>{{index}}-------{{age}} <button v-on:click="remove">删除</button></li>', methods: { remove:function(index){ this.$emit('removesingle',index); } } }) var vm = new Vue({ el:"#app", data:{ username: "zhangsan", allages: [18,19,20], }, methods: { removeage:function(index){ this.allages.splice(index,1) } } }); </script> </body> </html>
效果图:
解释下上面的代码吧:
首先我们希望是点击删除按钮,对应的数据能够被删除掉。
要知道的是,我们点击删除按钮触发的函数只能在组件的methods方法里的,而不能直接调Vue对象的methods方法,所以只能通过中间的组件元素来帮助过渡。
vue的methods方法可以直接获取到data中的数据,对它进行删除操作,又由于双向绑定,view层 的数据也会发生变化,这个也是我们想要的效果;但问题就是我们如何通过点击组件的删除按钮触发remove函数,在remove函数中如何去调用vue实例的removeage函数呢?这个时候就要用到自定义事件了,首先我们使用v-on绑定一个自定义的事件,当触发该事件时我们就可以调用removeage函数了,那这个事件要怎么触发呢?我们只要在remove函数中加上this.$emit('removesingle',index),就代表触发了removesingle事件,第二个参数是传给removesingle事件对应触发的removeage函数的参数。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~