第二十三篇:自定义事件(比如删除)

好家伙,贼绕,贼复杂

 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对象

秒啊

 

posted @ 2021-09-28 23:20  养肥胖虎  阅读(44)  评论(0编辑  收藏  举报