0

In VueJS, a child component can emit an event, for example:

this.$emit('toggle-button')

In the parent, we can listen to this event as follows:

<my-component v-on:toggle-button="doSomething"></my-component>

This works great. But I have a requirement where the event name (in this case, toggle-button) is stored in a variable or Vuex store. So, I don't have the exact event name but a variable or store with the name of the event.

In such a case what would be the syntax for referring that that event name in the on-click directive?

For example, let say we have:

let eventName = 'toggle-button'

How can I use this variable (eventName) instead of the exact event name (toggle-button) in the following:

<my-component v-on:toggle-button="doSomething"></my-component>

2 Answers 2

1

You could use $on(EVENT_NAME, CALLBACK) in this case:

// <my-component ref="foo" />
this.$refs.foo.$on(eventName, doSomething)

Vue.component('my-component', {
  template: `<button @click="$emit('click', $event)">Click</button>`
});

new Vue({
  el: '#app',
  mounted() {
    const eventName = 'click';
    this.$refs.foo.$on(eventName, this.doSomething);
  },
  methods: {
    doSomething() {
      alert('clicked');
    }
  }
})
<script src="https://unpkg.com/[email protected]"></script>

<div id="app">
  <my-component ref="foo" />
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Thank! I will try. And where should this code go in my parent template?
@asanas No problem :) The code should probably go in the mounted() lifecycle hook (see demo I just added).
Don't forgot to also deregister the event handler when its no longer needed, also you get a memory leak (also take care of the case when the value changes)
0

If you render your component using separate render function, this is easy:

export default {
    props: {
        eventName: {
            type: String,
        },
    },
    render: function (createElement) {
        return createElement('my-component', {
            on: {
                [this.eventName]: (event) => {
                    console.log('Received event!')
                }
            }
        })
    }
}

Render functions also come with ability to dynamically specify a name for the component, if that is also required for your app

1 Comment

This looks really promising. I'm just wondering if it's possible to use this in Nuxt?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.