vue中,子组件向父组件(子传父)使用$emit,传递一个或多个参数

vue中,子组件使用自定义组件向父组件传值时,一般会传递一个参数,但是传递多个参数怎么办呢?

1、传一个参数
// 子组件:
submit(){
	this.$emit('submit',this.id)
}
<!-- 在父组件中使用子组件 -->
<foods-edit  :foodsList="foodsList" @submit="handelFoods"></foods-edit>
<!-- 等同于 -->
<foods-edit  :foodsList="foodsList" @submit="handelFoods($event)"></foods-edit>
  • 绑定事件处理函数时,可以不带括号,形参则默认为事件对象;
  • 如果绑定时带上了括号,再想使用事件对象则需要传入$event作为实参。
// 父组件的方法中接收参数:
handelFoods(e) {
    // 事件处理函数
	console.log(e)
}
2、子组件向父组件传递一个值,并携带额外参数
// 子组件:
submit(){
	this.$emit('submit',this.id)
}
<!-- 在父组件中使用子组件  运用插槽 -->
<template slot="planned_amount" slot-scope="text, record">
  <!-- 在父组件中使用子组件 -->
   <foods-edit :text="text" :inputType="inputType" @submit="handelFoods(record,$event)"></foods-edit>
</template>
// 父组件的方法中接收参数:
handelFoods(record,e) {
    // 事件处理函数
	console.log(record,e)
}
  • 绑定事件处理函数时,record和 e v e n t 的 顺 序 不 做 要 求 , 但 是 按 照 v u e 事 件 绑 定 的 习 惯 , ∗ ∗ event的顺序不做要求,但是按照vue事件绑定的习惯,** eventvueevent通常放在实参列表末尾**。
3、传递多个参数
写法一(推荐)

在触发事件的父组件中加入arguments参数列表

// 子组件:
submit(){
	this.$emit('submit',JSON.stringify(this.foodsList),this.id)
}
<!-- 在父组件中使用子组件 -->
<foods-edit  :foodsList="foodsList" @submit="handelFoods(arguments)"></foods-edit>
// 父组件的方法中接收参数:
handelFoods(e) {
	// e[0]:第一个参数    e[1]  第二个参数
	console.log(e[0],e[1])
}
写法二

可以再父组件中接收的时候不接收参数 ,在方法中直接写参数,传递了几个写几个,一一对应。

// 子组件:向父组件传递了两个值
submit(){
	this.$emit('submit',this.value,this.text)
}
<!-- 在父组件中使用子组件 -->
<foods-edit  :foodsList="foodsList" @submit="handelFoods"></foods-edit>
handelFoods(param1,param2) {
	// param1:第一个参数    param2 第二个参数
	console.log(param1,param2)
}
  • 绑定事件处理函数时,不能携带括号!!!如果携带括号并且在括号内加了$event,只能拿到子组件传递过来的第一个参数。
写法三
// 子组件:向父组件传递了两个值
submit(){
	this.$emit('submit',this.value,this.text)
    // this.$emit('submit','11','文本')
}
<!-- 在父组件中使用子组件  运用插槽 -->
<template slot="planned_amount" slot-scope="text, record">
  <!-- 在父组件中使用子组件 -->
   <foods-edit :text="text" :inputType="inputType" @submit="handelFoods(record,arguments)"></foods-edit>
</template>
// 父组件的方法中接收参数:
handelFoods(record,args) {
    // 事件处理函数
	console.log(record,args)  // '11','文本'
}

arguments是方法绑定中的一个关键字,内部包括了所有方法触发时传递过来的实参。arguments和额外参数的位置谁先谁后不做要求,建议arguments放后面。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐