Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

vue.js - Programmatically bind custom events for dynamic components in VueJS

In my vuejs app I use dynamic component in the following way:

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

myComponent is a prop on the parent component which hold the actual component to inject. myComponentProps are also prop which holds the porps for the injected instance.

I would like to know how can I also dynamically bind listeners to the component - I have understand that I cannot send an object to v-on with multiple events.

I was thinking about adding it programatically however haven't found any info about how it can be done for Vue custom events (kind for addEventListener equivalent for custom events)

Any tip would be much appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With Vue 2.2+, you can programmatically add an event listener with $on(eventName, callback):

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) })
  }
})
<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...