[英]Listen for Foundation event in Vue.js?
我正在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?
谢谢!
基本上这可能归结为你的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)
}
事实上,这确实可以吸引这一事件。 问题在于,无论出于何种原因,基金会将模态移动到Vue 之外 ,并在模态初始化时将其附加到文档的底部。 这会导致Vue在launchModal
设置为false
时抛出错误,因为模式不再在 Vue中,并且Vue在尝试将其从DOM中删除时会抱怨。
既然如此,我建议你用你的v-if
该模式为内部 正在呈现非常缓慢的事情 。 这将导致像这样的组件。
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>
这是工作的例子 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.