我正在使用 Vue.js 构建一个具有以下一般结构的应用程序:
<app>
<filters-component></filters-component>
<div class="off-canvas-content">
<nav-component></nav-component>
<div class="row card-grid">
<card-component v-for="item in items">
<modal-component v-if="launchModal === true"></modal-component>
</card-component>
</div>
</div>
</app>
仅当 launchModal
的数据元素设置为 true 时(单击按钮启动模式后),这才允许我在 DOM 上呈现模式。这很好用,但我需要在它关闭时执行相反的操作。
根据 Foundation 的文档,Reveal(模态)组件在关闭时应发出一个名为 closed.zf.reveal
的事件。
如何在父元素(卡片组件)上监听此事件,然后在调用时将 launchModal
更改为 false?
谢谢!
最佳答案
从本质上讲,这可能会归结为,在您的 modal-component
中(将它们添加到 Modal.vue 中的脚本中)
methods:{
onModalClosed(){
this.$emit("modal-closed")
}
},
mounted(){
this.$el.addEventListener('closed.zf.reveal', this.onModalClosed)
},
beforeDestroy(){
this.$el.removeEventListener('closed.zf.reveal', this.onModalClosed)
}
或类似的东西,取决于哪个元素发出事件。如果其他一些元素发出了 closed.zf.reveal
事件,那么您可以向它添加一个 ref="modal"
,然后使用 this.$refs。 modal.addEventListener
和 this.$refs.modal.removeEventListener
。
那你就可以
<modal-component v-if="launchModal === true"
@modal-closed="launchModal = false">
</modal-component>
编辑
所以监听事件的问题是 Foundation 使用 jQuery 来触发事件。这意味着您不能使用 native 方法 (addEventListener
) 来监听它,您必须使用 jQuery 来监听它。所以从上面修改后的代码是这样的:
methods:{
onModalClosed(){
this.$emit("modal-closed")
}
},
mounted(){
$(this.$el).on('closed.zf.reveal', this.onModalClosed)
},
beforeDestroy(){
$(this.$el).off('closed.zf.reveal', this.onModalClosed)
}
事实上,这确实捕获了事件。问题在于,无论出于何种原因,Foundation 都会将模态移到 Vue 之外,并在初始化模态时将其附加到文档底部。当 launchModal
设置为 false
时,这会导致 Vue 抛出错误,因为模态不再在 Vue 中,并且 Vue 在尝试时会报错将其从 DOM 中移除。
既然如此,我建议您使用 v-if
inside things that are rendering very slowly 的模式.这将产生这样的组件。
Vue.component("modal", {
props:["show"],
template: "#modal-template",
watch:{
show(newVal){
if (newVal)
$(this.$el).foundation("open")
}
},
methods:{
onModalClosed(){
this.$emit("modal-closed")
}
},
mounted() {
new Foundation.Reveal($(this.$el))
$(this.$el).on("closed.zf.reveal", this.onModalClosed);
},
beforeDestroy() {
$(this.$el).off("closed.zf.reveal", this.onModalClosed);
}
});
模板是
<template id="modal-template">
<div class="reveal" data-reveal>
<div v-if="show">
Stuff that is expensive to render
</div>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
</template>
这是工作 example .
关于javascript - 在 Vue.js 中监听 Foundation 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43687275/