自定义事件

一、绑定事件:

定义:子给父传递数据:通过父组件给子组件绑定一个自定义事件。

 @或v-on

App.vue代码:

<Student @sendName="getName"/> 

Student是子组件,sendName:事件名称,getName:回调函数

Student.vue代码

使用this.$emit调用,第一个参数为:事件名称,第二个参数:传递的数据

methods: {

pressBtn() {

// 调用自定义事件

this.$emit('sendName',this.name); 

}

},

子组件添加ref

给子组件添加ref=”student”,用$on的方式添加,第一个参数:名称,第二个参数:回调函数。
 

mounted() {

this.$refs.student.$on("sendName",this.getName);

}

注意:

1:如果子组件调用原生事件 需要添加native,否则会当成自定义组件,如:

@click.native="show"

2:$once,只执行一次。

二、事件解绑:

解绑一个事件

this.$off(‘xxxx’ )    xxxx:事件名称

解绑多个事件

 this.$off([‘x1’,’x2’])   使用数组的形式。

解绑所有事件

this.$off()

销毁组件实例

this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。

案例 

App.vue

<template>
	<div >
	     <h1>班级信息:{{title}}</h1>
		 <hr/>
		 <!-- @click.native 原生js事件 @click.native="show"-->
		 <Person @getName="showName" ref="person" />
	</div>
</template>

<script>
   import Person from './components/Person.vue';
	
	export default {
		name:"App",
		data(){
			return {
			    title:"2209班",
			}
		},
		methods: {
			showName(name) {
				console.log("App得到了姓名",name);
			},
			showAge(age){
				console.log("App得到了年龄(this.refs.xxx.$on)",age);
			},
			show(){
				alert("123")
			}
		},
		components: {
			Person
		},
		mounted(){
			//第一个参数:自定义事件的名称,第二个参数:自定义事件的回调
			//$once 事件只执行一次
			this.$refs.person.$on("getAge",this.showAge);
		}
		
	}

</script>

<style>
	
	
</style>

components-Person

<template>
	<div>
		姓名:{{name}},年龄:{{age}}
		<button @click="sendName">发送信息给父组件</button>
		<button @click="sendAge">发送年龄给父组件</button>
		<button @click="offAge">解绑年龄</button>
		<button @click="mydestory">销毁组件实例</button>
	</div>
</template>

<script>
	export default{
		name:"Person",
		data(){
			return {
				name:"张三",
				age:19
			}
		},
		methods:{
			sendName(){
				// console.log("子组件",this.name);
				this.$emit("getName",this.name);
			},
			sendAge(){
				this.$emit("getAge",this.age);
			},
			offAge(){
				console.log("getAge 已解绑")
				this.$off("getAge");
			},
			// 销毁组件实例
			mydestory(){
				console.log("组件实例已销毁");
				this.$destroy();
			}
		}
	}
</script>

<style>
</style>

main.js

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值