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

Vue中如何仅初始化时将Prop赋值给响应式变量并避免覆盖?

Vue输入框值被Prop覆盖,无法保留用户输入

问题场景

  • 初始化时通过Prop的form_data.email为emailInput赋值
  • 输入新邮箱后按回车,emailInput被Prop的旧值重置,发送的始终是初始邮箱

相关代码

Input元素

<input
  type="text"
  class="text-[16px] text-light-text bg-main-background p-[11px]"
  name="email"
  ref="email"
  :value="emailInput"
  @keyup.enter="checkEmailAndSendCode"
/>

初始化逻辑

let emailInput = ref<string>("")
emailInput.value = props.form_data.email

处理函数

const checkEmailAndSendCode = () => {
  // TODO: check email

  console.log('we are sending email: ', emailInput.value)

  // Require code for the new email entered
  requireEmailCode(emailInput.value);

  // Show email code block
  state.email.isNewEmailEntered = true;
};

问题原因

  1. 单向绑定未同步用户输入:当前使用:value单向绑定emailInput,但未绑定@input事件将用户输入同步到emailInput,导致emailInput始终保留初始Prop值,用户输入的内容仅停留在输入框DOM中,未更新到响应式变量。
  2. 可能存在Prop监听逻辑:若组件中存在监听props.form_data.email变化并更新emailInput的代码(如watch),会导致输入后emailInput被Prop值覆盖。

解决方案

1. 同步用户输入到响应式变量

将单向绑定改为双向绑定v-model,自动同步用户输入和emailInput的值:

<input
  type="text"
  class="text-[16px] text-light-text bg-main-background p-[11px]"
  name="email"
  ref="email"
  v-model="emailInput"
  @keyup.enter="checkEmailAndSendCode"
/>

或者手动添加@input事件实现同步:

<input
  type="text"
  class="text-[16px] text-light-text bg-main-background p-[11px]"
  name="email"
  ref="email"
  :value="emailInput"
  @input="e => emailInput.value = e.target.value"
  @keyup.enter="checkEmailAndSendCode"
/>

2. 确保仅初始化赋值一次

  • 确认组件中没有监听props.form_data.email并更新emailInput的watch逻辑,若有则删除。
  • 初始化赋值仅在组件创建时执行一次,当前setup顶层的赋值方式已经满足,无需额外修改。

验证效果

修改后输入新邮箱,按下回车时控制台会打印用户输入的新邮箱值,且不会被Prop的旧值覆盖,同时验证码区块正常显示。

内容的提问来源于stack exchange,提问作者Thelambofgoat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:40:33