v-model in child components

If you’re having trouble using v-model for input elements in child components then welcome to the club. Here’s a quick way to solve it by using $emit to pass data back to parent:

App.vue:

<ChildComponent 
    v-bind:myvar="myvar"
    @myfunction="myfunction"
/>

<script>
export default {
    name: "App",
    components: {
        ChildComponent,
    },
    data: function() {
        return {
            myvar: "foo"
        }
    },
    methods: {
        myfunction(val) {
            this.myvar = val;
        }
    }
};
</script>

ChildComponent.vue:

<template>
    <input :value="myvar" @input="$emit('myfunction', $event.target.value)">
</template>

<script>
export default {
    name: 'ChildComponent',
    props: {
        myvar: String,
    }
};
</script>

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *