Vue實現table上下移動
阿新 • • 發佈:2019-01-09
結合Element元件,scope中有三個引數(row,cow,$index)分別表示行內容、列內容、以及此行索引值,
table上繫結陣列 :data=“tableList”
<el-table :data="tableList">
</el-table>
新增一列,裡面放上上移和下調兩個按鈕,並繫結上函式,將此行的索引值(scope.$index)作為引數,樣式根據需求自己調整:
<el-button icon="el-icon-arrow-up" :disabled="scope.$index === 0" @click="upFieldOrder(scope.$index)"></el-button> <el-button icon="el-icon-arrow-down" :disabled="scope.$index === tableList.length - 1" @click="downFieldOrder(scope.$index)"></el-button>
直接使用下面這種方式是錯誤的,雖然tableList的值變了,但是不會觸發檢視的更新:
upFieldOrder (index) {
let temp = this.tableList[index-1];
this.tableList[index-1] = this.tableList[index]
this.tableList[index] = temp
},
正確的上移函式:
upFieldOrder (index) { let temp = this.tableList[index-1]; Vue.set(this.tableList, index-1, this.tableList[index]) Vue.set(this.tableList, index, temp) },
同理,下移函式如下:
downFieldOrder (index) {
let i = this.tableList[index+1];
Vue.set(this.tableList, index+1, this.tableList[index])
Vue.set(this.tableList, index, i)
}
如此,前端的調整table順序功能便做好了,我不是在每一次點選都與後臺互動傳入新Order,在頁面銷燬時,一併提交:
destroyed() { let param = { infos: [] } this.tableList.forEach((dataItem,index) => { param.infos.push({ 引數1: dataItem.值1, 引數1: dataItem.值2, 引數順序: index }) }); // 呼叫後臺,並傳入 param changeTableOrder(param).then(res => { if(res.success=== true) { alert('順序調整成功') } }) }