组件的自定义事件

本文详细介绍了在Vue框架中父子组件之间的数据通信方法,包括通过props将父组件的函数传给子组件,子组件通过调用该函数传递数据,以及使用自定义事件进行通信的两种方式。无论是通过props传递函数还是利用$emit触发事件,都展示了Vue中组件间数据流动的灵活性。
摘要由CSDN通过智能技术生成

父子组件通信

子组件给父组件传递数据

1.通过 props :父组件向子组件传递一个函数型的 props。子组件通过 props 调用这个在父组件中定义的函数来传递数据。

父组件:

	<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
		<School :getSchoolName="getSchoolName"/>

		methods: {
				getSchoolName(name){
					console.log('App收到了学校名:',name)
				}
		}

子组件:

<button @click="sendSchoolName">把学校名给App</button>

props:['getSchoolName'],

methods: {
	sendSchoolName(){
		this.getSchoolName(this.name)
	}
},

2.通过自定义事件

2.1:父组件内自定义事件,子组件内触发这个事件并传递数据。

父组件:

<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) -->
<Student @atguigu="getStudentName" @demo="m1"/> 

getStudentName(name,...params){
		console.log('App收到了学生名:',name,params)
		this.studentName = name
},

子组件:

<button @click="sendStudentlName">把学生名给App</button>
methods: {
		sendStudentlName(){
		//触发Student组件实例身上的atguigu事件
		this.$emit('atguigu',this.name,666,888,900)
		// this.$emit('demo')
		// this.$emit('click')
},

2.2 父组件内定义 监听 事件,子组件内触发这个事件并传递数据。

父组件:

<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
	<Student ref="student" @click.native="show"/>
	mounted() {
		this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件
		// this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)
    },

子组件:

<button @click="sendStudentlName">把学生名给App</button>
methods: {
	sendStudentlName(){
		//触发Student组件实例身上的atguigu事件
	this.$emit('atguigu',this.name,666,888,900)
	// this.$emit('demo')
	// this.$emit('click')
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

卷不动的小毛

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

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

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

打赏作者

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

抵扣说明:

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

余额充值