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

Vue中如何获取输入框的修改后值?附场景代码

解决输入框值获取与日期更新同步问题

你当前的问题核心在于单向绑定和computed属性的只读特性:用:value绑定computed返回的值,只能把初始值渲染到输入框,但输入框的修改不会同步回去;而且computed完全依赖dates计算,只要dates没变化,它就一直返回原有结果,自然拿不到输入的新值。

给你两个可行的解决思路,推荐第一种:

方案一:本地维护状态 + 监听props更新

  1. 在组件内部用data维护本地日期状态,专门用来绑定输入框
  2. 用watch监听传入的dates,外部日期变化时同步更新本地状态
  3. 输入框改用v-model绑定本地状态,实现双向绑定

修改后的代码示例:

<template>
  <form method="post" @submit.prevent="updateShifts">
    <div class="text-center bg-slate-800 mt-2 rounded-lg">
      <span>Shift 1</span>
      <div class="flex items-center justify-between pb-2 px-4">
        <input 
          name="shift1_start"
          class="text-gray-900 w-[54px] px-1 text-center rounded border-2 border-gray-500 bg-white inline-flex items-center justify-center invalid:border-red-500 disabled:bg-slate-400 disabled:text-slate-800"
          pattern="^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$"
          maxlength="5"
          v-model="selectedDate.shift1_start"
        >
      </div>
    </div>
    <div class="text-center">
      <button type="submit" class="bg-orange-500 px-2 py-1 mt-2 rounded-lg text-white">Save</button>
    </div>
  </form>
</template>

<script>
export default {
  props: {
    dates: [Object, null]
  },
  data() {
    return {
      selectedDate: {
        nwd: '',
        shift1_start: ''
      }
    }
  },
  watch: {
    dates: {
      immediate: true, // 组件初始化时就执行一次同步
      handler(newDates) {
        if (newDates?.length) {
          this.selectedDate = {
            nwd: newDates[0].base_shift_nwd,
            shift1_start: newDates[0].base_shift1_start
          }
        }
      }
    }
  },
  methods: {
    updateShifts() {
      // 这里就能拿到输入框的最新值
      console.log(this.selectedDate);
      // 如果需要把修改后的值传给父组件,可通过emit事件
      // this.$emit('update-shifts', this.selectedDate)
    }
  }
}
</script>

方案二:给computed添加setter(适合需同步修改父组件数据场景)

如果业务需要把输入框的修改直接同步到父组件的dates,可以给computed属性添加setter,通过emit事件通知父组件更新:

<script>
export default {
  props: {
    dates: [Object, null]
  },
  methods: {
    updateShifts() {
      console.log(this.firstSelectedDate);
    }
  },
  computed: {
    firstSelectedDate: {
      get() {
        return {
          nwd: this.dates[0].base_shift_nwd,
          shift1_start: this.dates[0].base_shift1_start,
        };
      },
      set(newValue) {
        // 通知父组件更新dates,需父组件监听该事件并处理
        this.$emit('update-dates', {
          ...this.dates[0],
          base_shift_nwd: newValue.nwd,
          base_shift1_start: newValue.shift1_start
        })
      }
    }
  }
}
</script>

同时输入框要改为v-model="firstSelectedDate.shift1_start",父组件需监听update-dates事件来更新原有的dates数组。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 19:46:32