You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:05:25