【问题标题】:How to re-arrange array position coming from API in Vuejs?如何在 Vuejs 中重新排列来自 API 的数组位置?
【发布时间】:2021-12-13 21:35:50
【问题描述】:

props: {
    groups: Array,
  },
  computed: {
    groups: function(arr) {
      alert('hi')
    }
  },
  
<div v-for="(item, index) in groups" :key="item.id" :id="item.id" class="group-name" @click="isOnlySelected ? null : $emit('setSelectedItem', item.id)">
</div>

如何在前端重新排列来自 API 的数组位置?

我能够显示从 api 到前端的所有值。但我需要添加一些条件,比如对数组值进行排序。示例(我需要将 array[6] 位置更改为 array[1] 位置。

【问题讨论】:

  • 使用计算属性,根据您设置的任何条件返回排序后的数组。
  • @Terry 我已经获取了计算属性。但不知道如何采用排序数组....你能建议我一些代码吗
  • 如果不查看阵列数据样本就无法提供帮助?您可以省略代码中的所有获取逻辑,因为它们与您的问题完全无关。请查看如何创建minimal reproducible example
  • @Terry 我已经添加了响应数组数据。好吗?.....我不确定我在哪里错过了逻辑???

标签: javascript vue.js axios


【解决方案1】:

一个选项是使用一个计算属性来排序/交换你的数组。然后,您在 v-for 中使用该计算属性。

computed: {
  rearrangeDataset () {
    if (Array.isArray(this.dataset) && this.dataset.length) {
      // Do your sorting or swapping. Always return a value in a computed property.
      let tmp = this.dataset[2]
      this.dataset[2] = this.dataset[0]
      this.dataset[0] = tmp
      return this.dataset
    } else {
      return []
    }
  }
}

然后在你的 v-for 中使用这个计算:

<div v-for="(item, index) in rearrangeDataset" :key="item.id" :id="item.id" class="group-name" @click="isOnlySelected ? null : $emit('setSelectedItem', item.id)">
</div>

我看到您在处理程序(其 ID)中使用此数据集,因此我认为最好在计算属性中更改您的数据集并返回相同的数据集。

我在 codepen 为您创建了一个示例:https://codepen.io/LucasFer/pen/oNewOwv

请注意,您也可以使用 watch 来解决此问题。

【讨论】:

  • 很好的例子。非常有帮助..... :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多