vue+element项目实战:vue+element+Sortable实现表格行拖拽功能
1.mpm下载插件 :
npm install sortablejs --save
2.页面引入:
import Sortable from 'sortablejs'
以上步骤进行完毕,就可利用Sortable实现表格拖拽。
根据我的项目需求,下面是我的写法,请大家参考:
我项目中某个页面需要点击排序,用的是el的dialog弹窗
弹窗内对表格进行排序。
下面请大家参考代码:
3.打开排序的button按钮html
<el-button type="primary" icon="el-icon-sort" @click="Open">排序</el-button>
4.打开弹窗html,这里要注意的是要在el-table中 写上 row-key=“xxx”,xxx代表表格里面的某个属性
<el-dialog title="商品排序" :visible.sync="dialogFormVisible_table">
<el-link type="warning" disabled>此排序与移动端同步</el-link>
<el-table :data="tableData_"
border
id="table"
row-key="shopId">
<el-table-column align="center" prop="shopType" label="商品类别" width="auto">
</el-table-column>
<el-table-column align="center" prop="shopId" label="商品编号" width="auto"/>
<el-table-column align="center" prop="title" label="商品名称" width="auto"/>
<el-table-column align="center" prop="desc" label="商品详情" width="auto"/>
<el-table-column align="center" prop="price" label="商品价格" width="auto">
</el-table-column>
<el-table-column align="center" prop="thumbImg" label="商品图片" width="auto">
</el-table-column>
<el-table-column align="center" prop="ps" label="备注" width="auto">
</el-table-column>
</el-table>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible_table = false">取 消</el-button>
<el-button type="primary" @click="updateTable">确 定</el-button>
</div>
</el-dialog>
4.js代码
4.1打开弹窗
Open() {
this.dialogFormVisible_table = true;//打开弹窗
this.$nextTick(() => {
this.drawBodyWrapper = document.querySelector('.el-dialog__body tbody');//找element的标签
this.rowDrop()
})
},
4.2行拖拽
rowDrop() {
const tbody = this.drawBodyWrapper//drawBodyWrapper要在data变量里声明,data里面的变量我就不一一列出来了
const _this = this
Sortable.create(tbody, {
onEnd({newIndex, oldIndex}) {
const currRow = _this.tableData_.splice(oldIndex, 1)[0]
_this.tableData_.splice(newIndex, 0, currRow)//splice方法删除和添加
},
})
},
4.3 排序后将排序的结果提交给后端,根据后端所需要的数据情况而定,本项目是依据商品类别排序的
updateTable(){
for (let i in this.tableData_){
this.newId.push(this.tableData_[i]['shopId'])//newId在data里声明的是一个数组,把排序好的shopId push到newId里面 传给后端
}
axios.post('/xxxx/xxxx/',{lb:'xxxxxxxxx',art_no_l:JSON.stringify(this.newId)}).then(res=>{
if (res.data.code==="200"){
Message(res.data.msg)
this.dialogFormVisible_table=false
this.getShopDate()
}
})
},
以上代码逻辑是ok的,具体要按照自己的项目情况来定,相互学习,有问题请指教!!!
谢谢!!!