我正在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
的事件。
如何在父元素(card-component)上侦听此事件,然后在调用它时将launchModal
更改为false?
谢谢!
答案 0 :(得分:1)
基本上这可能会归结为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来触发事件。这意味着您无法使用本机方法(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外部,并在初始化模态时将其附加到文档的底部。这会导致Vue在launchModal
设置为false
时抛出错误,因为模式不再是在 Vue内部,而Vue在尝试将其从DOM中删除时会抱怨
在这种情况下,我建议您使用v-if
内部 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。