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

Vue+Buefy表单无法显示数据库已有日期拆分字段值

问题修复:拆分DateTime后无法显示原有值

核心问题

你在show方法里犯了逻辑错误:处理传入的tenancy对象后,生成dateForMovingIn和timeForMovingIn时,错误引用了this.tenancy.moveInDateTime——此时this.tenancy还没被更新为新处理的对象,仍然是初始的null,导致拆分出的日期时间为空,自然无法在字段中显示。

修复后的代码

<b-form-row>
  <b-col lg="6">
    <b-form-group :label="$t('Move in date')">
      <b-date-picker v-model="tenancy.dateForMovingIn"/>
    </b-form-group>
  </b-col>
  <b-col lg="6">
    <b-form-group :label="$t('Move in time')">
      <b-time-picker v-model="tenancy.timeForMovingIn"/>
    </b-form-group>
  </b-col>
</b-form-row>

<script>
export default { 
  data() {
    return {
      tenancy: {
        moveInDateTime: null,
        dateForMovingIn: null,
        timeForMovingIn: null,
        moveOutDateTime: null,
        dateForMovingOut: null,
        timeForMovingOut: null
      }
    }
  },
  methods: {
    show(tenancy) {
      const newTenancy = JSON.parse(JSON.stringify(tenancy));

      if (newTenancy.moveInDateTime) {
        newTenancy.moveInDateTime = new Date(newTenancy.moveInDateTime);
        newTenancy.dateForMovingIn = moment(newTenancy.moveInDateTime).format('YYYY-MM-DD');
        newTenancy.timeForMovingIn = moment(newTenancy.moveInDateTime).format('HH:mm');
      }

      if (newTenancy.moveOutDateTime) {
        newTenancy.moveOutDateTime = new Date(newTenancy.moveOutDateTime);
        newTenancy.dateForMovingOut = moment(newTenancy.moveOutDateTime).format('YYYY-MM-DD');
        newTenancy.timeForMovingOut = moment(newTenancy.moveOutDateTime).format('HH:mm');
      }

      this.tenancy = newTenancy;
    },
 
    submit() {
      this.tenancy.moveInDateTime = moment(`${this.tenancy.dateForMovingIn} ${this.tenancy.timeForMovingIn}`, 'YYYY-MM-DD HH:mm').toDate();
      this.tenancy.moveOutDateTime = moment(`${this.tenancy.dateForMovingOut} ${this.tenancy.timeForMovingOut}`, 'YYYY-MM-DD HH:mm').toDate();
    }
  }
}
</script>

关键修复点

  • 变量引用修正:拆分日期时间时,使用刚处理好的newTenancy.moveInDateTime,而非未更新的this.tenancy.moveInDateTime
  • 逻辑顺序调整:先完成所有字段的拆分处理,再把新对象赋值给this.tenancy,确保组件能拿到完整的字段值
  • 补全字段定义:在data里补上缺失的时间/日期字段初始定义,避免未定义报错
  • 提交类型统一:提交时把moment对象转成原生Date类型,适配后端常见的DateTime接收格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:45:38