Vue 学习笔记(五)自定义事件内容分发

Vue 中自定义事件内容分发

1.什么是内容分发

纯属说概念的话会过于呆板并且十分抽象不好理解,可以简单的将内容分发理解为在Vue中定义的函数通过传递的方式使得组件通过this.$emit(‘自定义事件名’,param…)进行调用,下面小编举例说明

现在有如下需求:
数据是通过for循环遍历出来的,需要对每个元素点击删除的时候,该对应元素会被删除

在这里插入图片描述

2.如何实现内容分发

1.双向绑定自定义数据以及展示数据

  Vue.component("todo",{
      template: '<div>\
                <slot name="todo-tip"></slot>\
                <ul>\
                <slot name="todo-item"></slot>\
                </ul>\
            </div>'
  })

  Vue.component("todo-tip",{
      props: ['title'],
      template:'<div>{{title}}</div>'
  })

  Vue.component("todo-item",{
      props: ['it'],
      template: '<li>{{it}} <button>删除</button></li>'
  })
                
  var vm = new Vue({
      el: "#app",
      data: {
          message: ['A','B','C','D','E','F','G'],
          title: '迪迦羊肉串'
      }
  })

展示数据:

<div id="app">
            <todo>
                    <todo-tip slot="todo-tip" :title="title"></todo-tip>
                    <todo-item slot="todo-item" :it="msg" v-for="(msg,index) in message" ></todo-item>
            </todo>
    </div>

2.为vm中绑定删除元素函数

 var vm = new Vue({
     		...
      methods: {
          rmItem: function(dex) {
                console.log("当前删除的是"+this.message[dex])
                this.message.splice(dex,1)
          }
      }
  })

3.将函数绑定到组件上

<todo-item  v-on:myclick="rmItem(index)"></todo-item>

4.在组件中创建函数并且调用

template: '<li>{{it}} <button @click="todo_rm">删除</button></li>', //在button中绑定函数
      methods: {
          todo_rm: function(){
              this.$emit('myclick')  // 自定义函数调用
          }
      }

5.点击删除按钮

在这里插入图片描述
整体来说其实还是比较绕的,所以在写自定义事件之前,要理清楚思路,便会豁然开朗了~

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值