在 Vue.js 监听基金会事件?

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 的事件。

如何在父元素(卡片组件)上监听此事件,然后在调用时将 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.reve‌​al', this.onModalClosed)
}

或类似的效果,具体取决于发出事件的元素。如果其他某个元素发出 closed.zf.reveal 事件,则可以向其添加 ref="modal",然后使用 this.$refs.modal.addEventListenerthis.$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.reve‌​al', this.onModalClosed)
}

事实上,这确实捕获了事件。问题在于,无论出于何种原因,Foundation 都会将模态 移到 Vue 的 之外,并在模态初始化时将其附加到文档底部。当 launchModal 设置为 false 时,这会导致 Vue 抛出错误,因为模态不再 inside 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">&times;</span>
    </button>
  </div>
</template>

这是工作 example