如何在Vue 3中将道具与组件的本地数据进行双向绑定?

谁能告诉我如何将组件的道具绑定到它自己的数据属性?例如,假设我有一个名为ModalComponent

的组件
<template>  // ModalComponent.vue
   <div v-if="showModal">
      ...
      <button @click="showModal = !showModal">close the modal internally</button>
   </div>
</template>

<script>
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      showModal: false,
    }
  }
}
</script>

<style>
</style>

现在考虑我将此模式用作父组件内部的可重用组件,使用外部按钮打开该模式的弹出窗口。

<template>
  <button @click="showChild = !showChild">click to open modal</button>
  <ModalComponent :show="showChild" />
</template>

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

<style>
</style>
如何使其在每次父级单击按钮时,通过将本地showModal绑定到道具show来弹出模式?当模式通过本地关闭按钮在内部关闭时,如果我再次单击父按钮,它是否会重新弹出?(我用的是Vue 3,以防万一)

如有任何帮助,我们将不胜感激。谢谢。


解决方案

这种情况的完美解决方案是使用v-model而不是传递道具:

在子组件中,将modelValue定义为属性,并使用$emit函数将其值发送给父组件:

<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>

在父组件中,只需使用v-model绑定值:

<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>

相关文章