赞
踩
需求:有时我们会面对类似这样的表格
图中的上移,下移功能需求明显要求我们改变两行数据的顺序。在实际开发中这种功能一般由后台来做,因为列表数据一般从后台获取刷新。即是我们点击”上移“,向后台请求接口,后台将数据库表格中的项交换位置,再把新的数据返回,前端拿到数据,重新刷新表格数据。
在此这篇博文仅设计到前端的数据处理及展示效果。因为我在开发过程中遇到了类似的需求,上移、下移功能不局限于表格,它也能是一个循环展示模块中的内容。
核心的JavaScript方法是:splice 对数组处理方法,删除或插入内容
代码例子:
- <template>
- <el-table :data="tableData" border style="width: 58%">
- <el-table-column fixed prop="date" label="日期" width="150"></el-table-column>
- <el-table-column prop="name" label="姓名" width="120"></el-table-column>
- <el-table-column prop="province" label="省份" width="120"></el-table-column>
- <el-table-column prop="city" label="市区" width="120"></el-table-column>
- <el-table-column prop="address" label="地址" width="300"></el-table-column>
- <el-table-column prop="zip" label="邮编" width="120"></el-table-column>
- <el-table-column fixed="right" label="操作" width="150">
- <template slot-scope="scope">
- <el-button
- type="text"
- size="small"
- @click="moveUp(scope.row, scope.$index)"
- :disabled="scope.$index === 0"
- >上移</el-button>
- <!-- 这里分别展示了判断是否上移下移的两种方案 -->
- <el-button
- type="text"
- size="small"
- @click="moveDown(scope.row, scope.$index)"
- :disabled="getFormLength(scope.$index)"
- >下移</el-button>
- <el-button type="text" size="small" @click="deleteItem(scope.$index)">移除</el-button>
- </template>
- </el-table-column>
- </el-table>
- </template>
-
- <script>
- export default {
- name: "splice",
-
- data() {
- return {
- disabled: true,
- tableData: [
- {
- date: "2016-05-02",
- name: "王小虎",
- province: "上海",
- city: "普陀区",
- address: "上海市普陀区金沙江路 1518 弄",
- zip: 200333,
- },
- {
- date: "2016-05-04",
- name: "张小龙",
- province: "深圳",
- city: "福田区",
- address: "车公庙",
- zip: 200333,
- },
- {
- date: "2016-05-01",
- name: "李牧",
- province: "江南",
- city: "鑫林",
- address: "南山区",
- zip: 200333,
- },
- {
- date: "2016-05-03",
- name: "哪吒",
- province: "普拉达",
- city: "纽约",
- address: "国家公园",
- zip: 200333,
- },
- ],
- };
- },
-
- methods: {
- // 上移
- moveUp(item, index) {
- this.tableData.splice(index - 1, 0, item); // 定位到点击位置的上一行,0即不删除如何元素,在此位置插入item
- this.tableData.splice(index + 1, 1); // 此时数组中有重复元素,把原来被挤下去的元素删除
- },
- // 下移
- moveDown(item, index) {
- this.tableData.splice(index + 2, 0, item);
- this.tableData.splice(index, 1);
- },
- // 添加
- // addItem() {
- // let item = {
- // date: "",
- // name: "",
- // province: "",
- // city: "",
- // address: "",
- // zip: "",
- // };
- // this.tableData.push(item);
- // },
- // 删除
- deleteItem(index) {
- console.log("delete");
- this.tableData.splice(index, 1);
- },
- // 控制下移按钮的显示于隐藏
- getFormLength(index) {
- if (index === this.tableData.length - 1) return true;
- else return false;
- },
- },
- };
- </script>
-
- <style lang="scss" scoped>
- </style>
-

例子的基础是elementui中表格的例子,添加了自定义的上移、下移和移除方法,做得完善一些,自然要处理隐藏掉第一行的上移按钮和最后一行的下移按钮,并提供相关的判别方法
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。