[Vuejs]-Vue how to use v-model on sync prop in child component

4👍

The child shouldn’t use v-model on the prop that is synced. Instead, it should use $emit('update:<prop>', value). However, it may make even more sense to use v-model from the parent and $emit('input', value) from the child:

// parent implementation
<child-component v-model="first_name" />

Then,

// child implementation
<template>
  <input type="text" @change="$emit('input', e)" :value="innerValue" />
</template>
<script>
export default {
  props: ['value'],
  data () {
    return {
      innerValue: ''
    }
  },
  mounted () {
    this.innerValue = this.value
  }
}
</script>

Edit

If you’d like to use the v-model approach within the child component, you’ll have to use it on the innerValue and emit when that changes. We can setup a watcher in the child:

// child component
watch: {
  innerValue: function (value) { 
    this.$emit('input', value)
  }
}

And then you can use v-model on your child’s component custom component implementation:

// child component
<template>
  <custom-component v-model="innerValue" />
</template>

Leave a comment