Vue组件自定义事件

自定义事件的作用:

  • 一种组件间通信的方式,适用于:子组件 ===> 父组件
  • 使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)

自定义事件的使用方式:

  • 本质:给子组件的实例对象上绑定自定义事件
  • 第一种方式:
    • 在父组件中,直接给子组件的标签上面添加自定义事件(相当于给子组件的实例对象上绑定自定义事件):<children @demo="test"/><children v-on:demo="test"/>
    • 子组件再利用组件实例对象的上的$emit函数触发自定义事件;
       父组件:
       <children @demo="test"/>
       子组件:
       this.$emit('demo','我是要传递给父组件的数据!!!')
  • 自定义事件也可以添加事件修饰符,如果想让事件触发一次,即可在自定义事件后加上.once
		<children @demo.once="test"/>
  • 第二种方式:
    • 利用ref获取子组件的实例对象,再给子组件的实例对象上绑定自定义事件:
    • 子组件再利用组件实例对象的上的$emit函数触发自定义事件;
	父组件:
	<children ref="test"/>
	......
	mounted(){
	   this.$refs.test.$on('demo',(data)=>{
	   		//data是子组件传给父组件的数据
			console.log(data)
		})
	}
	子组件:
	this.$emit('demo','我是要传递给父组件的数据!!!')

案例:

	父组件:
	<template>
	  <div id="app">
	    <Student @demo="test"/>
	  </div>
	</template>
	
	<script>
	import Student from './components/student.vue'
	export default {
	  name: 'App',
	  components: {
	    Student,
	  },
	  methods:{
	    test(data){
	      console.log('我是App组件,我收到了子组件传过来的数据',data);
	    }
	  }
	}
	</script>
	子组件:
	<template>
	  <div>
	    <ul>
	      <li>姓名:{{ name }}</li>
	      <li>年龄:{{ age }}</li>
	    </ul>
	    <button @click="send">点我将数据name发送给父组件</button>
	  </div>
	</template>
	
	<script>
	export default {
	  name: "Student",
	  data() {
	    return {
	      name: "张三",
	      age: 18,
	    };
	  },
	  methods:{
	      send(){
	          this.$emit('demo',this.name)
	      }
	  }
	};
	</script>

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值