组件中的emit

        我们从页面向子组件传递参数时,我们可以使用props;我们从页面向子组件传递模板片段时,可以使用slots;当我们需要子组件传递参数给调用它的页面时,我们可以使用emit进行参数传递。

例如:

<template>
	<view>
		<image :src="props.pic"></image>
		<view>{{props.goods_name}}</view>
		<view class="id_name">
			<slot name="s1"></slot>
		</view>
		<view> 
			<slot name="b1"></slot>
		</view>
		<!-- emit的用法 -->
		<button @click="onClick">emit</button>
	</view>
</template>

<script setup>
// const props = defineProps(['pic','goods_name'])

// emit演示
const emit = defineEmits(["add"])
// emit演示
function onClick(){
	emit('add',Math.random())
}

const props = defineProps({
	pic:{
		type:String,
		defaut:"../../static/logo.jpg"
	},
	goods_name:{
		type:String,
		defaut:"None"
	},
	obj_test:{
		type:Object,
		defaut(){
			return {pic:"../../static/logo.jpg",name:"None"}
		}
	}
})
</script>
<template>
	<view>
		<!-- <blog_Props pic="../../static/ai.jpg" goods_name="Picture1">
			<view> id : 123456</view>
			</blog_Props>
		<blog_Props pic="../../static/ai.jpg" goods_name="Picture1">
			<view> <button>这是一个按钮</button></view>
			</blog_Props> -->
			<blog_Props @add="onAdd" pic="../../static/ai.jpg" goods_name="Picture1">
				<template v-slot="s1">
					<view> id : 123456</view>
				</template>
				<template #b1>
					<view> <button>这是一个按钮</button></view>
				</template>
			</blog_Props>
			<view>{{num}}</view>
	</view>
</template>

<script setup>
	import {ref} from 'vue'
	const num = ref(0)
	const onAdd = function(e){
		console.log(e)
		num.value = e
	}
</script>

        在上述代码中,子组件中定义了一个传递参数的方法add,并配合一个onclick事件使用,我们在页面中调用子组件时,可以通过@add调用该方法,将该方法的返回值传到别的方法中,如:将返回值传到num中。当我们点击触发子组件中的onClick事件的时候,就会返回一个随机数,并通过onAdd方法将这个值赋给num,在页面上显示出来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

YoloMari

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

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

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

打赏作者

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

抵扣说明:

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

余额充值