【问题标题】:How to 2-way bind props with local data of a component in Vue 3?如何在 Vue 3 中将道具与组件的本地数据进行双向绑定?
【发布时间】:2021-10-27 23:23:23
【问题描述】:

谁能告诉我如何将组件的 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>

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

<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,以防万一)

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

【问题讨论】:

  • ModalComponent 应该发出一个事件而不是设置本地 showModal,这是双向绑定的常用方法。

标签: javascript vue.js vuejs3 two-way-binding vue-props


【解决方案1】:

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

在子组件中定义 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>

在父组件中只需使用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>

【讨论】:

猜你喜欢
  • 2021-09-02
  • 2019-06-10
  • 2021-11-04
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多