首页 > 解决方案 > 在Vue中使用计算函数基于多维数组过滤数组时遇到问题

问题描述

使用 vue 我试图更改/更新一个数组(draggables),其逻辑是如果对象存在于另一个数组数组(drozones)中,它将从draggables中删除

每个可拖动对象只能在与可拖动对象 dropID 匹配的多维数组的索引中找到。

我尝试过的每种方法要么返回所有可拖动项目,要么返回所有可拖动项目,要么删除不正确的可拖动项目。

// In this example I have three droppable and two drop areas, the first drop area can handle two droppable and the last area only one.

<div id="app">
  <ul>
    <li v-for="item in draggables">Item ID: {{item.id}}  - Dropzone ID: {{item.dropID}}</li>
  </ul>
</div>

data: {
    draggableItems: [{id: 0, dropID: 0 }, {id: 1, dropID: 0 }, {id: 2, dropID: 1 }],
    dropzones: [[{id: 1, dropID: 0 }], []]
},
computed : () {
   draggables () {
     return this.draggableItems.filter((item, index) => {
       console.log('item', item)
    
       return this.dropzones.filter((zone,i)  => {
          if (zone.length === 0) return
          return item.id !== zone[i].id
      })
    })
  }
}

这是的一些尝试,但还没有运气。谢谢你的帮助

标签: arraysvue.js

解决方案


您需要检测比较 2 个对象的键,或者您需要一个函数来比较对象。您可以尝试isEqual功能lodash或比较 JSON.stringify 的 2 个结果

new Vue({
  el: '#app',
  data: {
    draggableItems: [{id: 0, dropID: 0 }, {id: 1, dropID: 0 }],
    dropzones: [
        [   
        {id: 1, dropID: 0 }
      ], 
      []
     ]
  },
  computed: {
    draggables () {
        return this.draggableItems.filter((item, index) => {
        return !this.dropzones.some((zone,i)  => {
            
          return zone.some(zoneitem => JSON.stringify(item) === JSON.stringify(zoneitem))
        })
        })
    }
   }
})
</script>

推荐阅读