Blog>
Snippets

Handling events on VNodes

Illustrates attaching event listeners to VNodes and handling events using Vue's built-in modifiers.
// Vue 2.x example using createElement function:

new Vue({
  el: '#app',
  data() {
    return {
      message: 'Hello World!'
    };
  },
  methods: {
    handleClick(event) {
      alert(`You clicked me! ${this.message}`);
    }
  },
  render(createElement) {
    return createElement('button', {
      // Attach event listener
      on: {
        // Event type: 'click'
        click: this.handleClick
      }
    }, 'Click me!');
  }
});
Creates a Vue instance that mounts to an element with id 'app'. It uses the `createElement` function to create a VNode that represents a button. The `on` object is used to attach a 'click' event listener that triggers the `handleClick` method defined in the Vue instance's methods.
// Vue 3.x example using the h (alias for createElement) function

const { createApp, h } = Vue;

createApp({
  data() {
    return {
      message: 'Hello World!'
    };
  },
  methods: {
    handleClick(event) {
      alert(`You clicked me! ${this.message}`);
    }
  },
  render() {
    return h('button', {
      // Attach event listener with modifier (e.g., 'click.prevent' to prevent default behavior)
      onClick: this.handleClick
    }, 'Click me!');
  }
}).mount('#app');
Creates a Vue 3 application that mounts to an element with id 'app'. It uses the `h` function to create a VNode for a button. The event listener uses the `onClick` property rather than the `on` object. The `.prevent` modifier can be added to the event (e.g., 'onClick.prevent') to prevent the default action of the event.