vue:组件自定义事件、绑定、解绑事件
自定义组件绑定事件:
- 使用方法:在引入组件中的methods定义一个回调方法,在组件标签中使用如下两种方式自定义事件,去到引入的组件的中,使用
this.$emit("eventName",this.val,...)
1.<componentName ref="componentName"></componentName>
ref这种方法更加灵活,但是必须在钩子方法mounted()中定义,mounted(){this.$refs.componentName.$on("name",this.methodName)}
,可以在绑定自定义事件之前有其他操作,比如:定时器等
2.<componentName v-on:eventName="name"></componentName>
自定义组件解绑事件:
- 去到组件标签的组件methods中,调用this. o f f ( ) / t h i s . off()/this. off()/this.off(’‘eventName’’)/this.$off([“e1”,’‘e2’’]),暴力解绑所有的绑定事件
注意:
- 如果vc或者vm调用distroy(),那么所有的watch、事件等都不生效,但是原生js不会
this.$refs.xxx.$once
:自定义事件只触发一次