如何在Vue 3中将道具与组件的本地数据进行双向绑定? [英] How to 2-way bind props with local data of a component in Vue 3?

查看:51
本文介绍了如何在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>

这篇关于如何在Vue 3中将道具与组件的本地数据进行双向绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆