How to 2-way bind props with local data of a component in Vue 3?(如何在Vue 3中将道具与组件的本地数据进行双向绑定?)
本文介绍了如何在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中将道具与组件的本地数据进行双向绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在Vue 3中将道具与组件的本地数据进行双向绑定?


猜你喜欢
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07