【发布时间】: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