如何在 Vue 3 中将 props 与组件的本地数据进行 2 路绑定?

shi*_*asu 0 javascript vue.js two-way-binding vue-props vuejs3

谁能告诉我如何将组件的 prop 绑定到它自己的数据属性?例如,假设我有一个名为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>
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

如何使每次父母单击按钮时,通过将本地绑定showModal到 prop 来弹出模式show?当模式通过本地关闭按钮在内部关闭时,如果我再次单击父按钮,它会重新弹出吗?(我正在使用 Vue 3,以防万一)

任何帮助,将不胜感激。谢谢。

Bou*_*him 5

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

在子组件中定义modelValue为 prop 并使用函数将其值发送给父组件$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>
Run Code Online (Sandbox Code Playgroud)

在父组件中仅用于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>
Run Code Online (Sandbox Code Playgroud)