Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS. v-model in 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);
        }
    }
});
like image 856
Svetoslav Dimitrov Avatar asked Sep 16 '17 21:09

Svetoslav Dimitrov


1 Answers

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/

like image 76
craig_h Avatar answered Sep 25 '22 12:09

craig_h