我有一个自定义事件可以关闭模态窗口,只要组件是父母的直接子,它就可以完美地工作。但是,当我想从更深的嵌套组件中调用事件时,它就不起作用。
这是我的父组件:
<Modal @modal-close="close" />
这是我的关闭按钮&lt; modal&gt;
:
<a @click="$emit('modal-close')">CLOSE</a>
如所说,这有效。但是内部&lt; modal&gt;
我正在为&lt; modal&gt;
的内容导入一个组件,现在我想从内容组件中调用事件:
const emit = defineEmits(['modal-close']);
emit('modal-close');
我没有任何警告或错误。但是,父母组件&lt; modal&gt;
什么也不做。活动不可用吗?我该如何解决这个问题?
解决的方法:
我通过在父母中创建一个函数来关闭&lt; modal&gt;
并将其作为道具传递给孩子们,从而选择了非事实的方式。在我看来,这是最简单的解决方案,并且还提供了在关闭模式时添加自定义操作的灵活性。
这是我的父母组件:
const close = (data) {
// close the modal
// process data
};
<Modal :close="close" />
我的孩子组成部分:
const $$ = defineProps({
close: Boolean | Function,
});
<a @click="$$.close">CLOSE</a>
I have a custom event to close a modal window and it works perfectly as long as the component is a direct child of the parent. But when I want to call the event from a deeper nested component it doesn’t work.
Here is my parent component:
<Modal @modal-close="close" />
Here is my close button inside <Modal>
:
<a @click="$emit('modal-close')">CLOSE</a>
As said, this works. But inside <Modal>
I’m importing a component for the content of <Modal>
and now I want to call the event from inside the content component like this:
const emit = defineEmits(['modal-close']);
emit('modal-close');
I get no warning or errors. But the parent-parent component <Modal>
does nothing. Are events not available globaly? How can I solve this problem?
SOLVED:
I chose the non-event based way by creating a function in the parent for closing the <Modal>
and pass it as a prop to the children. It seems to me that this is the simplest solution and also provides flexibility to add custom actions when closing the modal.
This is my parent component now:
const close = (data) {
// close the modal
// process data
};
<Modal :close="close" />
And my child component:
const $ = defineProps({
close: Boolean | Function,
});
<a @click="$.close">CLOSE</a>
发布评论
评论(1)
一种方法(可能是最简单的)是使中间组件将事件引起。这意味着一个组件会聆听
模态粘液
事件,并将其发给其父。这可能是最简单的方法,但是它不是很可扩展,您可能会为一次性使用而做。VUE 3不提供全局侦听器(VUE2中的活动总线),但是您可以使用处理全球事件。
。 /events-api.html#event-bus“ rel =“ nofollow noreferrer”> docs
虽然还有另一个基于非事实的选项。
您可以使用
ref
变量,而不是听事件,而不是聆听事件。模态通常被用作单例/全球群体,因此可以在全球范围内访问该变量。如果您有单个模态,则可以从组件导出该变量,也可以使用提供/注入。One way (probably the simplest) is to get the intermediary components to bubble the events up. That would mean that a component listens to the
modal-close
event, and emits it to its parent. This may be the simplest way, but it's not very scalable and something you might do for a one-off use.Vue 3 doesn't provide a global listener (event bus in vue2), but you could use a library like mitt to handle global events.
— docs
There is another, non-event based option though.
Instead of listening to an event, you can use a
ref
variable that will manage open closed state. Modals are often handled as singletons/globals so the variable can be accessible globally. If you have a single modal, you can export that variable from the component or you can use Provide/Inject.