更新:现在它正常工作了。老实说,我不确定自己做了什么——我真的不记得改变了任何东西,但我相信这是由于大家的反馈,所以感谢所有帮助过我的人。
我有一个循环,根据数组中的对象生成表格行。无论我触发删除操作的是哪一行,总是删除数组中的最后一项。
数据——存储为“meetingPlans”
[
{
dow:"-T-R---",
endTime:"11:45:00",
startTime:"08:45:00"
},
{
dow:"--W----",
endTime:"12:45:00",
startTime:"10:45:00"
},
{
dow:"----F--",
endTime:"15:00:00",
startTime:"14:00:00"
}
]
模板
<tr v-for="(meetingPlan,meetingPlanIndex) in meetingPlans" :key="meetingPlanIndex">
<td>
-- stuff here doesn't matter --
</td>
<td>
-- stuff here doesn't matter either --
</td>
<td class = "pl-0">
<button v-on:click="removeMeetingPlan(meetingPlanIndex)" type = "button" class = "btn btn-danger btn-sm">
<i class = "fas fa-times"></i>
</button>
</td>
</tr>
Vue代码
var vm = new Vue({
el:"#dynamic-planning-column",
delimiters:["<%","%>"],
// This is defined server-side. "meetingPlans" is one of the properties of planData
data:window.planData,
methods:{
addReserveGroup:function(index){
this.reserveGroups.push({number:'',description:'',cap:''});
},
removeReserveGroup:function(index){
this.reserveGroups.splice(index,1);
},
addMeetingPlan:function(index){
this.meetingPlans.push({id:0,dow:'',startTime:'',endTime:'',timeslot:-1});
},
removeMeetingPlan:function(index){
this.meetingPlans.splice(index,1);
},
meetingPlanDowIsOdd:function(MeetingPlan){
return MeetingPlan.dow.includes('M') || MeetingPlan.dow.includes('W') || MeetingPlan.dow.includes('F');
}
}
});
对我来说,看起来应该能够工作。
尝试过的调试方式:
- 确保模板中的meetingPlanIndex是唯一值。 - 当我修改removeMeetingPlan()以输出index并输出this.meetingPlans[index]时,两个都是预期值。 - 当我修改removeMeetingPlan()为硬编码:this.meetingPlans.splice(0,1)时,它仍会删除最后一个项。
我尝试的解决方案是,我读到可以将:key设置为对象而不是数字,所以我修改了模板:
<tr v-for="(meetingPlan,meetingPlanIndex) in meetingPlans" :key="meetingPlan">
那样做可以成功删除正确的行,但是Vue会警告重复的键和使用非原始数据作为键。
还有什么其他尝试方法吗?
key
的不当使用,更新后的数组没有被正确渲染。 - skirtlemeetingPlans
声明在哪里?你能粘贴一下你的data
函数吗? - Ross Allen