[Vuejs]-How to 2-way bind props with local data of a component in Vue 3?

5👍

The perfect solution for this case is using v-model instead of passing a prop :

in child component define modelValue as prop and emit its value to the parent using $emit function:

<template>  // ModalComponent.vue
   <div v-if="modelValue">
      ...
      <button @click="$emit('update:modelValue',!modelValue)">close the modal internally</button>
   </div>
</template>

<script>
export default {
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
  },
  emits: ['update:modelValue'],

}
</script>

in parent component just use v-model to bind the value :

<template>
  <button @click="showChild = !showChild">click to open modal</button>
  <ModalComponent v-model="showChild" />
</template>

<script>
export default {
  components: {ModalComponent},
  data() {
    return {
      showChild: false,    
    }
  }
}
</script>

Leave a comment