我要做的是将发射名称作为字符串(例如'showComponent'
(从子级传递给父级,然后在emitAction(callbackName: string)
中调用另一个发射,并最终调用showComponent()
函数。
没有错误或警告。我做错了什么?
父组件:
<script setup lang="ts">
const showLoginPopup: Ref<boolean> = ref(false);
function showComponent() {
showLoginPopup.value = true;
}
const emit = defineEmits<{
(event: string): void;
}>()
function emitAction(callbackName: string) {
emit(callbackName);
}
</script>
<template>
<ActionVue @emitAction="emitAction" v-for="action in actions"
:title="action.title"
:description="action.description"
:buttonTitle="action?.buttonTitle"
:actionType="action.actionType" />
</template>
子组件:
<script setup lang="ts">
const props = defineProps<Action>();
const emit = defineEmits<{
(event: 'emitAction', callbackName: string): void;
}>()
</script>
<template>
<button @click="emit('emitAction', props.actionType)">
{{ props.buttonTitle }}
</button>
</template>
第二次发射除了将事件发射到父组件的父组件之外,不会做任何事情。我建议简单地运行基于发射名称的功能
子级:
<button @click="emit('showComponent')"
父级:
<ActionVue @showComponent="showComponent()">
如果真的想要基于字符串值调用函数,可以动态调用存储在当前应用程序实例上的函数:
父组件:
<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const app = getCurrentInstance()
function emitAction(callbackName: string) {
// if callbackName === 'showComponent', runs function showComponent()
app.setupState[callbackName]();
}
function showComponent() {
showLoginPopup.value = true;
}
}
在template
标记中调用emit
时,它需要是$emit(…)
。请参阅我的Codepen示例,特别是我如何在子组件中调用emit。
<!-- works -->
<button @click="$emit('foo', 'bar')">Click</button>
<!-- does not work; "emit" is not a defined function for the component -->
<button @click="emit('foo', 'bar')">Click</button>