基于Vue+element-ui 的Table树

前面和大家分享过自己封装的table了
这次和大家分享一个table的树 无限级的树 自己以前也看过网上写的树 都是里面带折叠的那种的 但是发现一个问题就是我新增了数据进入就会表格会重新渲染了 有点体验不是很好的感觉 然后还有就是样子也不太好看 我就想起了以前的学习ThinkPHP 里面分享了一个table的树 觉得挺不错的 我也想搞一个用前端的方式去写一个
一开始想去再去找找 (自己有点懒 哈哈哈)

效果大致的样子


这个是我以前看到的样子觉得挺不错的
来自己也实现一下

html部分

<template>
 <div>
      <comTable v-model="accessdata" :loading="loading">
        <el-table-column min-width="200" label="权限名称" align="center">
          <template slot-scope="scope">
            <div style="width:100%;text-align: left;">
              {{`${scope.row._type}${scope.row.AccessName}`}}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="AccessKey" min-width="200" label="关键字" align="center">
        </el-table-column>
        <el-table-column prop="AccessIcon" min-width="200" label="图标" align="center">
        </el-table-column>
        <el-table-column min-width="200" label="节点类型" align="center">
          <template slot-scope="scope">
            {{`${scope.row.AccessType == 1 ? '菜单' : '功能'}`}}
          </template>
        </el-table-column>
        <el-table-column prop="AccessSort" min-width="200" label="排序" align="center">
        </el-table-column>
        <el-table-column prop="Remark" min-width="200" label="备注" align="center">
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template slot-scope="scope">
            <Button type='primary' size='small' :disabled=" scope.row.AccessType == 1 ? (getPower('add') ? false : true) : true" style="margin-right:5px" @click="btnadd(scope)">
              添加下级
            </Button>
            <Button type='success' size='small' :disabled="getPower('update') ? false : true" style="margin-right:5px" @click="btnupdate(scope)">
              修改
            </Button>
            <Button :type="scope.row.Status == 1 ? 'warning' : 'info'" size='small' :disabled="getPower('update') ? false : true" style="margin-right:5px" @click="btnstop(scope)">
              {{scope.row.Status == 1 ? '停用' : '启用'}}
            </Button>
            <Poptip confirm title="你确定要删除吗?" @on-ok="btndel(scope)" transfer>
              <Button type='error' size='small' :disabled="getPower('del') ? false : true" style="margin-right:5px">删除</Button>
            </Poptip>
          </template>
        </el-table-column>
      </comTable>
 </div>
</template>
复制代码

这个里面的comTable组件就是上次封装的table组件了

主要的数据处理部分

我们返回的数据是有父子关系的

class CommonWay {
  /**
   * description:对数组的分页处理
   * author:
   * date:
   * @param {number} [pageNo=1] 页码
   * @param {number} [pageSize=10] 每页显示条数
   * @param {any} [obj=[]] 待分页的数组
   *  @param {Boolean} [iscreateNewdata=true] 是否创建新的数据
   * @returns 返回新的数组
   * @memberof CommonWay
   */
  pagination(pageNo = 1, pageSize = 10, obj = [], iscreateNewdata = true) {
    var array = [];
    if (iscreateNewdata) {
      array = JSON.parse(JSON.stringify(obj));
    } else {
      array = obj;
    }
    var offset = (pageNo - 1) * pageSize;
    return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
  }

  /**
   * 功能描述:获取树状table
   * 创建时间:2018-09-21
   * 创建者:xyw
   * @param {*} [data=[]] 有父子级关系的数据
   * @param {string} [pid='ParentId']
   * @param {number} [def=0]
   * @returns
   * @memberof CommonWay
   */
  TreeTable(data = [], pid = 'ParentId', def = 0) {
    let Newdata = [];
    data.map((item, index) => {
      if (item[pid] == def) {
        item._type = "";
      } else if (item.children) {
        item._type = this.GetNotbsp(item._level) + "─ ";
      } else {
        if (index == data.length - 1) {
          item._type = this.GetNbsp(item._level) + " └─ ";
        } else {
          item._type = this.GetNotbsp(item._level) + "─ ";
        }
      }
      Newdata.push(item);
      if (item.children) {
        Newdata.push(...this.TreeTable(item.children, pid, def));
      }
    })
    return Newdata;
  }

  /**
   * 功能描述:获取有子节点字符串
   * 创建时间:2018-09-21
   * 创建者:xyw
   * @param {*} _level
   * @returns
   * @memberof CommonWay
   */
  GetNotbsp(_level) {
    let nb = '';
    for (let index = 1; index < _level; index++) {
      if (index == _level - 1) {
        nb += ` ├`
      } else {
        nb += ` │`
      }
    }
    return nb;
  }

  /**
   * 功能描述:获取没有子节点字符串
   * 创建时间:2018-09-21
   * 创建者:xyw
   * @param {*} _level
   * @returns
   * @memberof CommonWay
   */
  GetNbsp(_level) {
    let nb = '';
    for (let index = 1; index < _level - 1; index++) {
      nb += ` │`
    }
    return nb;
  }

  /**
   * 功能描述:把数据处理成父子关系
   * 创建时间:2018-09-21
   * 创建者:xyw
   * @param {*} data 数据
   * @param {string} [id='id'] 主键键值
   * @param {string} [pid='parentId'] 父级键值
   * @returns
   * @memberof CommonWay
   */
  treeDataTranslate(data, id = 'id', pid = 'parentId') {
    var res = []
    var temp = {}
    for (var i = 0; i < data.length; i++) {
      temp[data[i][id]] = data[i]
    }
    for (var k = 0; k < data.length; k++) {
      if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
        if (!temp[data[k][pid]]['children']) {
          temp[data[k][pid]]['children'] = []
        }
        if (!temp[data[k][pid]]['_level']) {
          temp[data[k][pid]]['_level'] = 1
        }
        data[k]['_level'] = temp[data[k][pid]]._level + 1
        temp[data[k][pid]]['children'].push(data[k])
      } else {
        res.push(data[k])
      }
    }
    return res
  }
}

export default CommonWay

复制代码
<script>
/**
功能描述:权限管理
创建时间:2018-09-18
创建者:xyw
 */
import comTable from '../common/comTable_new'
import { getTableData, Accessdel, Accessadd, Accessupdate, QueryTableData } from '../../api/system/access'
import commomway from '../../assets/js/commonway'
import Appmixin from '../AppMixin/'
export default {
  name: "sysaccess",
  mixins: [Appmixin],
  data() {
    return {
      ModalLoading: false,
      accessname: '',
      accessmodal: false,
      modaltitle: '',
      action: '',
      loading: false,//表格数据加载状态
      switchdisabled: false,//是否禁用启用switch
      formValidate: {
        Id: 0,
        AccessName: "",
        AccessKey: "",
        AccessIcon: "",
        ParentId: 0,
        AccessSort: 0,
        AccessStatus: 1,
        AccessType: 1,
        ParentName: '',
      },
      ruleValidate: {
        AccessSort: [
          { message: '只能是数字', trigger: 'change', pattern: /^(([1-9]\d{0,3})|0)(\.\d{0,2})?$/, }
        ],
        AccessName: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ],
        AccessKey: [
          { required: true, message: '请输入关键字', trigger: 'blur' },
        ]
      },
      menuList: [],
      menuListTreeProps: {
        label: 'AccessName',
        children: 'children'
      },
      defaultCheckedKeys: [],
      defaultExpandedKeys: [],
      accessdata: []
    };
  },
  components: {
    comTable
  },
  created() {
    this.loading = true;
    this.init();
  },
  methods: {
    init() {//页面加载初始数据
      getTableData().then(re => {
        if (re.data.status == 'ok') {
          let comway = new commomway();
          let { menuData, accessData } = { menuData: JSON.parse(JSON.stringify(re.data.data)), accessData: JSON.parse(JSON.stringify(re.data.data)) };
          this.accessdata = comway.TreeTable(comway.treeDataTranslate(accessData, 'Id', 'ParentId'));
          this.loading = false;
        }
      })
    },
    btnadd(params) {
      this.$refs['formValidate'].resetFields();
      this.formValidate = {
        Id: 0,
        AccessName: "",
        AccessKey: "",
        AccessIcon: "",
        ParentId: params.row.Id,
        AccessSort: 0,
        AccessStatus: 1,
        AccessType: 1,
        ParentName: params.row.AccessName
      }
      this.switchdisabled = false;
      this.accessmodal = true;
      this.action = 'add';
      this.modaltitle = '添加下级权限信息';
    },
    btnstop(params) {
      params.row.AccessStatus = params.row.AccessStatus == 1 ? 2 : 1;
      Accessupdate(params.row.Id, params.row).then(re => {
        if (re.data.status == 'ok') {
          this.init();
          this.$Message.success((params.row.AccessStatus == 1 ? '启用' : '停用') + '成功!');
        } else {
          this.$Message.error((params.row.AccessStatus == 1 ? '启用' : '停用') + '失败!');
          console.log(re.data.msg);
        }
      })
    },
    btnupdate(params) {
      this.$refs['formValidate'].resetFields();
      Object.keys(params.row).map(key => {
        this.formValidate[key] = params.row[key];
      })
      this.accessmodal = true;
      this.switchdisabled = false;
      this.action = 'update';
      this.modaltitle = '修改权限信息';
    },
    btndel(params) {
      Accessdel(params.row.Id).then(re => {
        if (re.data.status == 'ok') {
          this.init();
          this.$Message.success('删除成功!');
        } else {
          this.$Message.error('删除失败!');
          console.log(re.data.msg);
        }
      })
    },
    menuListTreeCurrentChangeHandle(data, node) {
      this.formValidate.ParentId = data.Id;
      this.formValidate.ParentName = data.AccessName;
    },
  }
};
</script>
复制代码

emmm 就是这样的吧 有啥好的建议阔以提提 嘻嘻

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值