vue.jscustom-componentv-model

Using v-model on custom component


When I start typing in the input field I want to get this data in console, but currently it is empty. What am I doing wrong?

HTML:

<products-list v-model="product.name" v-on:keyup="productName"></products-list>

JS:

Vue.component('products-list', {
    template:
        `<input class="product_name form-control" contenteditable="true"></input>`,
});

var app = new Vue({
    el: '#app',
    data: {
        items: items,
        product: {
            name: "",
        }
    },
    methods: {
        productName: function() {
            console.log(product.name);
        }
    }
});

Solution

  • v-model uses the @input event by default, so if you want to use v-model on a custom component you need to emit the input event to the parent. So, in your component, you simply do:

    <input class="product_name form-control" @input="$emit('input', $event.target.value)" />

    Now in your parent you can do:

    <products-list v-model="product.name"></products-list>

    You can see the full example on this JSFiddle: https://jsfiddle.net/7s2ugt11/