VueJS中props数据无法在v-model中显示问题求助
解决子组件props初始化本地数据后textarea绑定为空的问题
问题原因
子组件初始化时,父组件传递的comment props可能还未完成异步加载(比如modalInfo.comment是接口请求后才赋值的),此时localComment会被初始化为空值。而Vue的data属性不会自动跟随props的更新同步,导致后续props拿到真实值时,localComment也不会更新,最终textarea显示为空。
解决方案
方案1:通过watch监听props变化
监听comment props的更新,实时同步到localComment:
props: ['comment'], data() { return { localComment: this.comment, }; }, watch: { // 监听comment的变化,更新本地数据 comment(newVal) { this.localComment = newVal; } }
方案2:使用带setter的computed属性(更推荐)
如果需要同时支持本地修改和props响应式,用computed的get/set方法适配v-model的双向绑定需求:
props: ['comment'], computed: { localComment: { get() { return this.comment; }, set(val) { // 若需要将本地修改同步回父组件,可触发自定义事件 this.$emit('update:comment', val); } } }
此时父组件需要改为双向绑定写法:
<ChangeCommentModal v-model:comment="modalInfo.comment" />
额外优化点
父组件模板中无需写this,直接引用数据即可:
<ChangeCommentModal :comment="modalInfo.comment" />
内容的提问来源于stack exchange,提问作者Arnaud
相关产品推荐
相关产品推荐

