以编程方式绑定VueJS中动态组件的自定义事件

时间:2018-01-14 14:55:34

标签: vue.js vuejs2

在我的vuejs应用程序中,我以下列方式使用动态组件:

<mycomponent>
  <component ref="compRef" :is="myComponent" v-bind="myComponentProps"></component>
  <div class="my-buttons">        
    <my-button label="Reset" @click="reset()"/>
  </div>
</mycomponent >

myComponent是父组件的prop,它包含要注入的实际组件。 myComponentProps也是支持注入实例的porps的支柱。

我想知道如何动态地将侦听器绑定到组件 - 我已经理解I cannot将对象发送到具有多个事件的v-on。

我正在考虑以编程方式添加它但是没有找到有关如何为Vue自定义事件执行的任何信息(类似于自定义事件的addEventListener

任何提示都会非常感激!

1 个答案:

答案 0 :(得分:27)

使用Vue 2.2+,您可以通过编程方式添加$on(eventName, callback)的事件监听器:

&#13;
&#13;
condition
&#13;
new Vue({
  el: '#app',
  created() {
    const EVENTS = [
      {name: 'my-event1', callback: () => console.log('event1')},
      {name: 'my-event2', callback: () => console.log('event2')},
      {name: 'my-event3', callback: () => console.log('event3')}
    ]

    for (let e of EVENTS) {
      this.$on(e.name, e.callback); // Add event listeners
    }

    // You can also bind multiple events to one callback
    this.$on(['click', 'keyup'], e => { console.log('event', e) })
  }
})
&#13;
&#13;
&#13;

使用Vue 2.6+,您可以在模板中add an event listener dynamically

&#13;
&#13;
<script src="https://unpkg.com/vue@2.6.8/dist/vue.min.js"></script>
<div id="app">
  <div>
    <!-- v-on:EVENTNAME adds a listener for the event -->
    <button v-on:click="$emit('my-event1')">Raise event1</button>
    <button v-on:click="$emit('my-event2')">Raise event2</button>
    <button v-on:click="$emit('my-event3')">Raise event3</button>
  </div>
  <div>
    <!-- v-on shorthand: @EVENTNAME -->
    <button @click="$emit('my-event1')">Raise event1</button>
    <button @click="$emit('my-event2')">Raise event2</button>
    <button @click="$emit('my-event3')">Raise event3</button>
  </div>
</div>
&#13;
new Vue({
  el: '#app',
  data: {
    eventname: 'click',
  },
  methods: {
    handler(e) {
      console.log('click', e.target.innerText)
    }
  }
})
&#13;
&#13;
&#13;

您还可以使用<script src="https://unpkg.com/vue@2.6.8/dist/vue.min.js"></script> <div id="app"> <button @[eventname]="handler">Raise dynamic event</button> <!-- Set dynamic key to null to remove event listener --> <button @click="eventname = null">Unbind event</button> </div>声明性地绑定多个事件侦听器:

&#13;
&#13;
v-on="{event1: callback, event2: callback, ...}"
&#13;
new Vue({
  el: '#app',
  methods: {
    onClick() { console.log('click') },
    onKeyUp(e) { console.log('keyup', e.keyCode) }
  }
})
&#13;
&#13;
&#13;