父组件监听子组件事件

文章目录

  • 过程
  • 监听子组件事件
  • 配合额外参数使用$emit


过程

过程分为两步:

1.子组件通过$emit()方法发出自定义事件,$emit()方法语法为:

$emit(eventName,[arg1,arg2,arg3,…])

其中eventName为事件名称,arg1、arg2、arg3等为可选的额外参数;

2.父组件在其模版通过v:on指令(简写为@)监听自定义组件

一、监听子组件事件

定义了组件"counter",它由<button>按钮组成,点击按钮会发出自定义事件"counter-add"。在根组件范围内,使用了该组件,因而可以在<counter>标签上可以通过v-on指令(指@)监听到"cpunter-add"事件,并在时间处理程序中对数据num进行自增。

<div id="app">
    <h2>当前计数器的值:{{num}}</h2>
    <counter v-on:counter-add="num++"></counter>
    <p>{{msg}}</p>
</div>
Vue.component('counter',{
    template:'<button @click="add">计数器</button>',
    methods:{
        add:function(){
            this.$emit('counter-add')
        }
    }
})

二、配合额外参数使用$emit

当点击给出建议按钮时,会从子组件内部arr数组中随机选取一项,在发出advice事件的同时将数据传给事件处理程序

<div id="app">
    <div calss="'outer">今天天气好,我准备
        <div class="inner">{{activity}}</div>
    </div>
    <advice @advice=""receiveAdvice></advice>
 </div>
Vue.component('advice',{
    data(){
        return{
            arr:['吃','喝','玩','乐']
    }
        },
    template:'<button @click="giveAdvice">给出建议</button>',
    methods:{
         giveAdvice:function(){
             let msg=this.arr[Math.floor(Math.random()*this.arr.length)]
             this.$emit('advice',msg)
         }
     }
 })

 


在Vue中,组件可以通过监听组件事件来获取组件的状态或者触发一些操作。具体实现方法如下: 1.在组件中定义一个事件,并在需要触发该事件的地方使用`$emit`方法触发该事件,例如: ```javascript // 组件中定义事件 this.$emit('child-event', 'hello from child component') ``` 2.在组件中使用`v-on`指令监听组件事件,并在回调函数中处理事件,例如: ```html <!-- 组件监听组件事件 --> <child-component v-on:child-event="handleChildEvent"></child-component> ``` ```javascript // 组件中处理组件事件 methods: { handleChildEvent(data) { console.log(data) // 输出:'hello from child component' } } ``` 另外,在Vue 2中,还可以使用`@hook`事件监听组件的生命周期事件,例如: ```html <!-- 组件监听组件生命周期事件 --> <child-component v-on:hook:mounted="handleMounted"></child-component> ``` ```javascript // 组件中处理组件生命周期事件 methods: { handleMounted() { console.log('child component mounted') } } ``` 在Vue 3中,可以使用类似上面的`@hook`事件监听组件的生命周期事件,例如: ```html <!-- 组件监听组件生命周期事件 --> <child-component v-on:hook:mounted="handleMounted"></child-component> ``` ```javascript // 组件中处理组件生命周期事件 methods: { handleMounted() { console.log('child component mounted') } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值