前言
在某些场景,子组件回传值到父组件时,我需要传入额外的参数去执行该方法,但在方法内,只能取到子组件回传的那个值,额外传入的取不到
比如该子组件是一个可复用的组件,并且是通过v-for循环出来的,这个时候的父组件也就是有了多个相同的子组件,在做数据处理时候,我需要以index做为唯一性,所以在每个子组件回传时候,都需要额外的传入index,但事实是按正常的写法是没有办法取到额外参数的。
解决方案
在父组件绑定子组件的方法加入一个$event即可,$event=> 子组件传递过来的值,如果是子组件传多个值,直接用arguments即可。
<!-- 父组件 -->
<li v-for="(item, index) in list" :key="index">
<!-- 单值 接收 -->
<child @test="getChild(arguments, index)"></child>
<!-- 多值 接收 -->
<!-- <child @test="getChild($event, index)"></child> -->
</li>
<!-- 子组件 -->
<template>
<div>
<button @click="toFather">提交</button>
</div>
</template>
<script>
export default {
data: {
return {
value1: '值1',
value2: '值2',
value3: '值3'
}
},
methods: {
toFather() {
// 传递 单个 值
this.$emit("test", value1);
// 传递 多个 值
// this.$emit("test", value1, value2,value3);
},
},
}
</script>