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

Vue+Vuetify+Axios+Django实现CRUD数据表时新增不刷新、编辑框为空求助

问题根因与修复方案

两个问题的核心诱因都是前后端字段名/大小写不匹配,附带异步执行顺序错误,按以下步骤修复即可:

问题1:新增数据后需刷新才显示的修复

  • 根因:后端返回的字段为小写id/size/weight,表格表头绑定的也是对应小写字段,但你本地editedItem用的是大写ID/Length/Weight作为键名,新增时推送到info数组的对象键名和表格绑定字段不匹配,渲染时识别不到值,刷新后重新拉取后端的标准字段数据才会正常显示。
  • 修复步骤:
    1. 统一data中editedItem、defaultItem的字段名,和后端返回、表头绑定的字段保持完全一致:
// 原错误配置
editedItem: {
  ID: '',
  Weight: 0,
  Length: 0,
},
defaultItem: {
  name: '',
  Weight: 0,
  Length: 0,
},
// 修改为正确配置
editedItem: {
  id: '',
  weight: 0,
  size: 0,
},
defaultItem: {
  id: '',
  weight: 0,
  size: 0,
},
  1. 调整save方法的执行顺序,避免异步请求未完成就重置数据:将this.close()挪到请求的then回调内,防止数据还没处理完就清空编辑项:
save () {
  if (this.editedIndex > -1) {
    getAPI.put('calibration/sizeweight/'+this.editedItem.id,{
      id:this.editedItem.id,
      weight:this.editedItem.weight,
      size:this.editedItem.size
    })
    .then(response=>{
      console.log(response)
      Object.assign(this.info[this.editedIndex], this.editedItem)
      this.initialize()
      this.close()
    })
  } else {
    getAPI.post('calibration/sizeweight',{
      id:this.editedItem.id,
      weight:this.editedItem.weight,
      size:this.editedItem.size
    })
    .then(response=>{
      console.log(response)
      this.info.push(this.editedItem)
      this.initialize()
      this.close()
    })
    .catch(error => { 
      console.log(error.response.data)
      this.close()
    })
  }
},

问题2:编辑对话框为空的修复

  • 根因:编辑时传入的item是从info数组获取的后端标准字段数据(键为id/size/weight),但原editedItem的键为大写不匹配,赋值后表单绑定的字段找不到对应值,所以显示为空。
  • 修复步骤:完成上述字段统一的修改后,这个问题会自动解决,如果仍有异常,可以在editItem方法中手动做字段映射兜底:
editItem (item) {
  this.editedIndex = this.info.indexOf(item)
  // 兜底字段映射,确认每个键对应正确的值
  this.editedItem = {
    id: item.id,
    weight: item.weight,
    size: item.size
  }
  this.dialog = true
},

额外优化点

原deleteItemConfirm方法中先删本地数据再发请求,可能出现请求失败但本地数据已删除的不一致问题,建议调整为请求成功后再修改本地数据:

deleteItemConfirm () {
  getAPI.delete('calibration/sizeweight/'+this.editedItem.id)
  .then(response=>{
    console.log(response)
    this.info.splice(this.editedIndex, 1)
    this.closeDelete()
  })
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 05:12:02