VueJs 2发出自定义事件触发,但没有"听到"

时间:2017-08-09 08:06:31

标签: javascript events vue.js

可能不可能,但我有一个对象扩展了Vue / VueComponent(试过两个)$emits一个通常会在其父级上捕获的自定义事件。

请参阅此笔:https://codepen.io/anon/pen/MvmeQp?editors=0011并观看控制台。

class nonVueComponent extends Vue {
  constructor(age,...args){
    super(args)
    console.log('new Blank Obj')

    setTimeout(() => {
      console.log('customEvent event does fire, but nothing hears it. Probably because it isnt in the DOM?', age)
      this.$emit('customEvent', `custom event from nonVueComponent...${age}`)  
    },500)

  }
}

Vue.component('test', {
  template: `<div>
               {{content}}
                <child :childAge="age" @customEvent="customEvent"></child>
                <child-secondary @secondaryEvent="customEvent"></child-secondary>
  </div>`,  
  props: {},
  data () {
    return {
      content: 'hello from component!',
      age : 20
    }
  },
  methods : {
    customEvent(data){
      console.log('PARENT: custom event triggered!', data)
      this.content = data
    },
    secondaryEvent(data){
      console.log('PARENT: !!secondary custom event triggered', data)
      this.content = data
    }
  }
})

Vue.component('child',{
  template: `<div>+- child {{childAge}}</div>`,
  props: ['childAge'],
  data () {
    outsideOfVue: new nonVueComponent(this.childAge)
  }
})

Vue.component('child-secondary',{
  template: `<div>+- secondary event</div>`,
  mounted(){
    setTimeout( ()=>{
      this.$emit('secondaryEvent', 'from secondary event....')  
    },125 )
   }
})

let vm = new Vue({ el: '#app'})

除了使用eventBus之外,还有其他方法可以让<child>的活动进入和退出吗?也许让nonVueComponent成为混合?

感谢。

1 个答案:

答案 0 :(得分:0)

代码:https://codepen.io/anon/pen/EvmmKa?editors=0011

发出事件的对象应该是子级辅助的对象。 尝试将实例传递给nonVueComponent的构造函数。

class nonVueComponent extends Vue {
  constructor(age,comp,...args){
    super(args)
    console.log('new Blank Obj')

    setTimeout(() => {
      console.log('customEvent event does fire, but nothing hears it. Probably because it isnt in the DOM?', age)
      comp.$emit('customEvent', `custom event from nonVueComponent...${age}`)  
    },500)

  }
}