跳至主要內容

0纠错本

Mr.Dylin...小于 1 分钟5.vue

$emit 会自动携带函数的参数吗?

官方文档上没有$emit或者const emit=defineEmits(['handleTest'])能自动携带函数的参数的说明,但是我时不时总有种默认携带参数的错觉,但是经过测试,emit是不会自动携带函数参数的,需要手动传参,才会把参数传递给事件监听器的回调函数。

<script setup>
/* 测试demo */
// 祖父组件
import Parent from './components/Parent.vue'

function handleTest(record) {
  console.log('结果:',record);
}
</script>

<template>
  <Parent msg="Vite + Vue" @handleTest="handleTest" />
</template>

<script setup>
// 父组件
import Son from './Son.vue';
defineEmits(['handleTest'])
</script>

<template>
  <Son @handleTest="$emit('handleTest')" />
</template>

<script setup>
// 子组件
const emit=defineEmits(['handleTest'])
function handleTest(e){
  emit('handleTest',e)
}
</script>
<template>
  <div>
    子组件:<button type="text" @click="handleTest">测试按钮</button>
  </div>
</template>

父组件需要手动传参,才会把子组件携带的信息传递给祖父组件

<Son @handleTest="(record)=>$emit('handleTest',record,otherMsg)" />
上次编辑于:
贡献者: zddbic