如何在Vue.js中重新排列从API接口获取的数组元素位置
实现方案
- 首先修复你现有代码的两个问题:
- computed属性和props属性都命名为
groups,会触发命名冲突 - 计算属性的getter不需要传入参数,你写的
groups: function(arr) { ... }是错误写法,需要通过this.groups访问props传入的原始数组
- computed属性和props属性都命名为
- 不要直接修改props传入的原始
groups数组,props为只读属性,直接修改会抛出Vue警告,我们在计算属性中拷贝数组后再做排序操作
代码修改
JS逻辑部分
props: { groups: Array, }, computed: { // 单独命名排序后的数组 sortedGroups: function() { // 浅拷贝原数组,避免修改原props const copyGroups = [...this.groups] // 边界判断:数组长度不足7时不做移动操作,避免报错 if (copyGroups.length <= 6) return copyGroups // 取出索引6的元素,插入到索引1的位置 const targetItem = copyGroups.splice(6, 1)[0] copyGroups.splice(1, 0, targetItem) return copyGroups } }
模板部分
把v-for的遍历对象替换为排序后的计算属性即可:
<div v-for="(item, index) in sortedGroups" :key="item.id" :id="item.id" class="group-name" @click="isOnlySelected ? null : $emit('setSelectedItem', item.id)"> </div>
通用扩展
如果需要频繁调整元素位置,可以封装通用的数组移动方法:
// 通用方法:将数组arr中索引from的元素移动到索引to的位置 const moveArrayItem = (arr, from, to) => { if (from < 0 || to < 0 || from >= arr.length || to >= arr.length) return arr const item = arr.splice(from, 1)[0] arr.splice(to, 0, item) return arr } // 计算属性简化为: sortedGroups() { return moveArrayItem([...this.groups], 6, 1) }
内容的提问来源于stack exchange,提问作者T dhanunjay
相关产品推荐
相关产品推荐

