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

Vue.js为v-for渲染的列表项添加删除按钮后无法正常删除条目问题

问题原因

  • 拼接删除接口URL时直接使用了整条数据对象:点击删除按钮时传入的是当前行的完整数据对象latest_information,URL字符串拼接时会自动将对象转为[object Object]格式,最终导致请求路径不符合后端要求。
  • 存在两处潜在隐患:一是v-for遍历未指定唯一key属性,不符合Vue渲染规范;二是data中latest_informations初始值声明为对象,但实际存储的是接口返回的列表数组,类型不匹配可能导致异常。

修复方案

1. 修改模板部分的v-for声明

给v-for添加key属性,避免Vue渲染警告:

<tr v-for="latest_information in latest_informations" :key="latest_information.id">

2. 修正删除方法的URL拼接逻辑

从传入的对象中取出id字段来拼接接口路径:

onDeleteConfirmSend(latest_information) {
  this.$auth.api.delete(`admin/latest_informations/${latest_information.id}.json`)
      .then(response => {
        this.$router.push({name: 'AdminLatestInformationIndex', query: {toast_type: 'deleted'}})
      })
      .catch(err => {
        this.$errorHandlers.initial(err);
      })
}

3. 修正data中的初始值声明

将列表初始值改为空数组,和后续存储的类型保持一致:

data() {
  return {
    latest_informations: [],
  }
},

可选优化:修复无效的console日志

原代码中setData方法里的console.log(latest_informations)会报变量未定义错误,需移到接口请求成功的回调中,且要加this访问实例属性:

setData(query) {
  this.$loading.load(this.$auth.api.get(`admin/latest_informations.json`, {params: query})
      .then(response => {
        this.latest_informations = response.data.latest_informations
        console.log(this.latest_informations) // 移到此处才会打印接口返回的真实数据
      })
      .catch(err => {
        this.$errorHandlers.initial(err);
      }));
},

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

相关产品推荐
方舟 Agent Plan

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

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