js實現數組內相鄰元素上移,下移


實現效果:

 即需要實現當前元素與相鄰元素交換位置,

當上移時,則是當前元素與上一元素調換位置;當下移時,則是當前元素與下一元素調換位置。

 

實現代碼:

js:

//點擊上移
clickUp(index){
  this.swapArray(this.tableData, index-1, index);
},
//點擊下移
clickDown(index){
  this.swapArray(this.tableData, index, index+1);
},
//數組元素互換位置
swapArray(arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
},

html:

<el-table-column label="順序調整" min-width="80" align="center">
  <template slot-scope="scope">
    <div class="img_style">
      <img src="@/assets/images/up_01.png" v-if="scope.$index == 0">
      <img src="@/assets/images/up.png" @click="clickUp(scope.$index)" v-else>
      <img src="@/assets/images/down_01.png" v-if="scope.$index == tableData.length - 1">
      <img src="@/assets/images/down.png" @click="clickDown(scope.$index)" v-else>
    </div>
  </template>
</el-table-column>

 

注意:

1.思想就是在數組中交換兩個元素的位置,使用splice()的替換;

2.上移是跟上一元素交換位置,下移是跟下一元素交換位置,不同體現在調用調換方法時傳入的index參數不同。

3.參考鏈接:https://www.cnblogs.com/dearxinli/p/6802151.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM