【问题标题】:Vue.js Remove a Nested Object from ArrayVue.js 从数组中删除嵌套对象
【发布时间】:2025-02-25 14:40:02
【问题描述】:

我有一个位置数组,每个位置都有几个事件。我想为用户提供删除整个位置以及位置事件的能力。我使用 $remove 进行这项工作。我还想为用户提供从某个位置删除单个事件的能力。这就是我卡住的地方。

这里是html:

<div class="wrapper" v-for="location in locations">
  <h2>
    {{ location.id}}: {{ location.street_address }}
    <a href="javascript:;" @click="deleteLocation(location)">
      <i class="fa fa-trash pull-right"></i>
    </a>
  </h2>
  <hr>
  <ul>
    <li v-for="event in location.events">
      {{ event.location_id }}.{{ event.id }}: {{ event.title }}
      <a href="javascript:;" @click="deleteEvent(event)">
        <i class="fa fa-trash pull-right"></i>
      </a>
    </li>
  </ul>
</div>

这里是javascript:

new Vue({
  el: 'body',
  data: {
    locations: [{
      id: 1,
      street_address: '123 Oak',
      events: [{
        id: 1,
        location_id: 1,
        title: 'Oak Street Event 1'
      }, {
        id: 2,
        location_id: 1,
        title: 'Oak Street Event 2'
      }]
    }, {
      id: 2,
      street_address: '456 Pine Street',
      events: [{
        id: 3,
        location_id: 2,
        title: 'Pine Street Event 1'
      }, {
        id: 4,
        location_id: 2,
        title: 'Pine Street Event 2'
      }]
    }, {
      id: 3,
      street_address: '789 Elm Street',
      events: [{
        id: 5,
        location_id: 3,
        title: 'Elm Streem Event 1'
      }, {
        id: 6,
        location_id: 3,
        title: 'Elm Street Event 2'
      }]
    }]
  },
  methods: {
    deleteLocation(location) {
        this.locations.$remove(location);
        console.log(location);
    },
    deleteEvent(event) {
        this.locations.events.$remove(event);
        console.log(event);
    }
  }

这是一个小提琴JSFiddle

如果有人可以看一下,我将不胜感激!

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    this.locations 是一个位置数组。该数组不包含events 属性;数组的各个元素都可以。您需要将位置和事件传递给您的deleteEvent

    <a href="javascript:;" @click="deleteEvent(location, event)">
    

    deleteEvent(location, event) {
        location.events.$remove(event);
        console.log(event);
    }
    

    【讨论】:

    • 非常感谢@roy-j!这非常有效,我现在明白它为什么有效了!