Vue3:子组件使用自定义事件向父组件传参

起因:封装组件需要将子组件中修改好的数据回传到父组件

刚开始用defineModel双向绑定进行数据修改,但是直接传原始数据,组件的通用性降低(可能是自己太菜了不会写),会导致传参时非常的繁琐,增加代码量,因此想到了使用自定义事件来将数据回传到父组件。

但是发现使用自定义事件回传的参数,父组件接收不到,使用console.log打印数据显示undefined

旧代码如下:

父组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<CommonInput v-model="inputValue" @test="handleTest()" />
</template>

<script setup>
import { ref } from "vue";

const inputValue = ref();

const handleTest = (data)=>{
console.log(data.value)
}

</script>

子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<input v-model="model" />
<button @click="test()">Submit</button>
</template>

<script setup>
const model = defineModel();

const emit = defineEmit(['test'])

const data = ref('test`s Data')

const test = ()=>{
emit('test',data)
}

</script>

点击子组件的按钮,在浏览器的控制台会输出undefined,这表示在父组件中并没有接收到子组件通过自定义事件传递过来的参数或者说子组件的参数并没有传递出去。

随后我仔细翻阅了官方文档以及一些介绍自定义事件的博客文章,最后才发现,原来在使用自定义事件的时候,绑定的方法(函数)要省去小括号,可以使得参数正常传递并且将所有参数都写出来

新代码:

父组件

1
2
3
4
5
6
7
8
9
10
11
12
<template>
<CommonInput v-model="inputValue" @test="handleTest" />
</template>

<script setup>
import { ref } from "vue";

const inputValue = ref();

const handleTest = (data)=>{
console.log(data.value)
}

子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<input v-model="model" />
<button @click="test">Submit</button>
</template>

<script setup>
const model = defineModel();

const emit = defineEmit(['test'])

const data = ref('test`s Data')

const test = ()=>{
emit('test',data)
}

</script>

将代码修改成这样,父组件中就可以正常的接收到参数了。