Vue 2 - 从click或input事件触发时$ emit的不同行为

时间:2017-02-24 12:06:59

标签: javascript vuejs2 eventemitter

在下面(https://www.trisoft.ro/blog/56-symfony-redirecting-from-outside-the-controller),由下面的click事件触发的$ emit按预期工作。输入事件触发的$ emit(/似乎是)以相同的方式连线,但是父母没有收到$ emit。

<div id="app">
  {{ message }}
  <child-comp 
    :prop="property" 
    @emitted="receiveEmit" 
    @emittedFromInput="receiveEmitFromInput"
  ></child-comp>
 {{ otherMessage }}
</div>


Vue.component('child-comp', {
  template: '<div><button @click="sendEmit">emit</button><input type="text" @input="onInput"><p v-if="inputEventFired">The input event fired</p></div>',
  data: function() {
    return {
      inputEventFired: false
    };
  },
  methods: {
    onInput: function(e) {
      this.inputEventFired = true;
      this.$emit('emittedFromInput', 'never see this');
    },
    sendEmit: function() {
      this.$emit('emitted', 'can change from click event that emits');
    }
  }
});

new Vue({
  el: '#app',
  data: function() {
    return {
      message: 'allo',
      otherMessage: 'cannot change this from input event that emits'
    };
  },
  methods: {
    receiveEmit: function(val) {
      this.message = val;
    },
    receiveEmitFromInput: function(val) {
      alert('i do not happen')
      this.message = val;
    }
  }
});

为了使上述内容更具可读性,子组件的模板是

<div>
  <button @click="sendEmit">emit</button>
  <input type="text" @input="onInput">
  <p v-if="inputEventFired">The input event fired</p>
</div>

1 个答案:

答案 0 :(得分:0)

SO以外的人对此有所帮助,我将在此处发布他们的信息。这里的问题既不是事件也不是发射器,而是(我的无知)html的不区分大小写。似乎@someCamelCasedEvent实际上是作为@somecamelcasedevent传递给javascript的。 working fiddle

  this.$emit('emitted-from-input', 'never see this');


<child-comp 
  @emitted="receiveEmit" 
  @emitted-from-input="receiveEmitFromInput">
</child-comp>