Blog>
Snippets

Using v-model in Render Functions

Create a render function example that shows how to properly bind v-model to a custom input component.
Vue.component('custom-input', {
  model: {
    prop: 'value',
    event: 'input'
  },
  props: ['value'],
  render: function(createElement) {
    // Create an input element and bind the value and input event
    return createElement('input', {
      attrs: {
        type: 'text'
      },
      domProps: {
        value: this.value
      },
      on: {
        // When input event is triggered on the input element
        // $emit the 'input' event with the current value
        // This keeps the parent's v-model in sync with the child component
        input: (event) => {
          this.$emit('input', event.target.value);
        }
      }
    });
  }
});
This code snippet creates a Vue component named 'custom-input' using the model option to define v-model behavior. The 'value' prop is used to keep the value in sync with the parent component, and 'input' is the event that will update the value. Inside the render function, an input element is created and the necessary bindings to the 'value' and 'input' event are set up. The input event listener will emit the 'input' event along with the new value whenever the user types in the input, thus keeping the parent's v-model in sync with the custom component.
new Vue({
  el: '#app',
  data: {
    customValue: ''
  },
  template: '<div><custom-input v-model="customValue"></custom-input><p>{{ customValue }}</p></div>'
});
This code snippet initializes a new Vue instance and mounts it to an element with the id 'app'. A data property 'customValue' is defined, which will be bound to the 'custom-input' component using v-model. The template includes the 'custom-input' with v-model directive and displays the value of 'customValue' in a paragraph tag. As the custom input is updated, the bound value 'customValue' will update as well and will be reflected in the paragraph tag.