简体   繁体   English

Vue.js 中的事件处理

[英]Event handling in Vue.js

I have a situation where in an event is fired from parent component is being listen to by several child components.我有一种情况,其中从父组件触发的事件正在被多个子组件监听。

e.g.
Parent Component: emit -> "orderReceived"
Child Component1( Tab1): on-> "orderReceived" -> fetch array1 from server
Child Component2( Tab2): on-> "orderReceived" -> fetch array2 from server

when both these tabs are opened, everything works fine.当这两个选项卡都打开时,一切正常。 What I'm struggling with is, destroying event listeners on Tab1 and still be able to listen on Tab 2. ( when the tab1 is closed).我正在努力的是,销毁 Tab1 上的事件侦听器,但仍然能够在 Tab 2 上侦听。(当 tab1 关闭时)。 Right now if the listeners of Tab1 are destroyed, it disables listeners on Tab 2 as well.现在,如果 Tab1 的侦听器被销毁,它也会禁用 Tab 2 上的侦听器。

Thanks in advance.提前致谢。

The event must removed from component which was listening not both, You need to use $off , to just removed selected event, not all events from the specific component only, not to both该事件必须从不是两个都侦听的组件中删除,您需要使用$off来删除选定的事件,而不是仅从特定组件中删除所有事件,而不是两个

const ChildComponent1 = {
  methods:{
    orderReceived(){
      //orderReceived event emit
    }
  },
  created(){
    EventBus.$on('YOURCONTENT', this.orderReceived)
  },
  beforeDestroy(){
    EventBus.$off('YOURCONTENT', this.orderReceived)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM