Vue的子传父

利用props传递函数实现

原理:将回调函数通过props传到子组件中,在合适地方调用

<!-- 父组件 -->
<template>
	<div>
		<Child :show="show"></Child>
	</div>
</template>
<script>
	export default {
		methods: {
			show(value) {
				console.log('子组件调用了父组件的show方法,携带的参数为:' + value)
			}
		}
	}
</script>
<!-- Child子组件 -->
<template>
	<div>
		<button @click="send()">点击给父组件传递数据</button>
	</div>
</template>
<script>
	export default {
		props: ['show'],
		methods: {
			send() {
				this.show(123);
			}
		}
	}
</script>

利用自定义事件实现

原理:将自定义事件绑定在子组件上,在子组件中调用$emit方法,并携带参数,触发该自定义事件,从而获取参数。

<!-- 父组件 -->
<template>
	<div>
		<!-- 第一种绑定自定义事件方式:直接绑定在子组件上 -->
		<Child @zidingyiEvent="getValue"></Child>
		<!-- 第二种绑定自定义事件方式:利用$on方法 -->
		<Child ref="child"></Child>
	</div>
<template>
<script>
	export default {
		methods: {
			getValue(value, ...args) {
				console.log('子组件给父组件传的值为:' + value + ',' + args);
			}
		},
		mounted() {
			this.$refs.child.$on('zidingyiEvent', this.getValue);
		}
	}
</script>
<!-- 子组件child -->
<template>
	<div>
		<button @click="send()">点击给父组件传递数据</button>
		<button @click="unbind()">解绑自定义事件</button>	
	</div>
</template>
<script>
	export default {
		data() {
			name: 'wuwu'
		},
		methods: {
			send() {
				this.$emit('zidingyiEvent', this.name, 1, 2, 'a');
			},
			unbind() {
				this.$off(); // 解绑所有自定义事件
				this.$off('zidingyiEvent'); // 解绑单一自定义事件
				this.$off(['zidingyiEvent', 'otherEvent']); // 解绑多个自定义事件
			}
		}
	}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值