Warm tip: This article is reproduced from stackoverflow.com, please click
vue.js

Binding component prop on input and instance variable

发布于 2020-03-29 12:46:58

In the following example, I have the vue instance variable "formTerms" that I want to bind to the component property "abc", which itself is bound to the inputfield in its template. When changing the input's value, I want the instances "formTerms" variable to get that value. However, the code does not seem to work.

JS:

Vue.component('terms',{
    model: {
        prop: 'abc',
        event: 'submit',
    },
    props: ['abc'],
    template: '<div><input type="text" name="terms" class="form-control" title="" @change="submit" :value="abc"/></div>',
    methods: {
        submit: function() {
            this.$emit('submit', this.abc);
        }
    }
});
var vm = new Vue({
    el: '#id',
    data: {
        formTerms: ''
    },

});

HTML:

<terms v-model="formTerms"></terms>
Questioner
Ferenjito
Viewed
92
Troy Kessler 2020-01-31 16:58

If you want to bind a v-model to a custom component you have to do it like this

Vue.component('terms',{
    props: ['value'],
    template: '<div><input ref="input" type="text" name="terms" class="form-control" title="" @input="$emit('input', $refs.input.value)" :value="value"/></div>'
});
var vm = new Vue({
    el: '#id',
    data: {
        formTerms: ''
    },

});

then you can use your component in the parent like you did

<terms v-model="formTerms"></terms>