组件的自定义事件

自定义事件:一种组件间通信的方式,适用于:子组件 → 父组件

使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。

1.绑定事件(父组件)

        HTML(标签)里的绑定方式:v-on;

        JS(Vue)里绑定方式: vue对象.$on(“事件名”,事件处理函数);

2.触发事件(子组件)

         vue对象.$emit(“事件名”,参数);

//子组件:
Vue.component('button-counter',{
	template: "<input type='button' v-on:click='incrementCounter' v-model='counter' />",
	data:function(){
		return {
			counter:0
		}
	},
	methods:{
		incrementCounter:function(){
			this.counter += 1
			this.$emit('increment')
		}
	}
});

//父组件:

<div id="app1">
    <p>{{ total }}</p>
    <button-counter v-on:increment="incrementTotal"></button-counter>
</div>

var app1 = new Vue({
	el: '#app1',
	data:{
		total:0
	},
	methods:{
		incrementTotal:function(){
			this.total += 1;
		}
	}
});

3.解绑事件

this.$off('increment') //解绑组件上的increment事件

this.$off(['increment','increment02']) //解绑组件上多个自定义事件

this.$off() //解绑组件上所有的自定义事件

        当组件被销毁时,绑定的事件也自然是失效的。 

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只小可乐吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值