【无标题】

vue基础学习-自定义事件分发

Vue this.$emit(‘事件名’,‘参数数据’)
官网
记录学习的一些问题,组件如何对Vue对象的数据进行删除。涉及到参数传递与事件分发。

  1. 在vue的实例中增加了methods对象并定义了一个名为removeTodoltems的方法
//2.定义数据
    new Vue({
        el:"#vue",
        data:{
            message:"你好",
            title:"自定义组件",
            todoItems:['1','2','3']

        },
        methods:{
            removeItem(index){
                console.log("删除了"+this.todoItems[index]+"ok")
                this.todoItems.splice(index,1)//一次删除一个元素
            }
        }

    });
  1. 修改todo-items待办内容组件的代码,增加一个删除按钮,并且绑定事件!
//    1.现在自定义一个组件
//这里用反斜杠代替字符串
       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>'
     })
    Vue.component("todo-items",{
        props:['item','index'],
        template:'<li>{{item}}---{{index+1}}<button @click="remove">删除</button></li>',
        methods:{
            remove(index){
                this.$emit('remove',index)
            }
        }
    })
  1. 修改todo-items待办内容组件的HTML代码,增加一个自定义事件,比如叫remove,可以和组件的方法绑定,然后绑定到vue的方法!
<div id="vue">
    {{message}}
    <todo>
        <todo-title slot="todo-title" title="title"></todo-title>
        <todo-items slot="todo-items" v-for="(item,index) in todoItems" :index="index" v-bind:item="item" v-on:remove="removeItem"></todo-items>
    </todo>
</div>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值