el-tree和el-table相关使用

文章目录

      • el-tree实现模糊查询
      • el-tree实现node节点增删改
      • el-tree 实现节点懒加载
      • el-tree获取所有选中的当前节点
      • el-tree获取当前节点及其选中父节点
      • el-table 获取多选行的所有节点
      • el-table 动态添加删除行数据
      • vue+element ui实现table表格行的上下移动
      • el-table动态添加实现元素校验
      • el-tree通过条件控制节点的操作
      • el-table 实现动态拖拽
      • el-form 实现动态添加并实现校验
      • el-table 动态增行通过dialog操作并将数据回显到table中
      • v3实现table行的可选择展开

el-tree实现模糊查询

<template>
  <div class="app-container">
    <el-input placeholder="请搜索" prefix-icon="el-icon-search" v-model="filterText">el-input>
    <el-tree :data="epTree" default-expand-all :props="defaultProps" :expand-on-click-node="false" ref="tree" :filter-node-method="filterNode">el-tree>
  div>
template>

<script>
export default {
  data () {
    return {
      epTree: [
        {
          id: 1,
          label: '一级公司',
          children: [
            {
              id: 11,
              label: '一级子公司1',
              children: [
                {
                  id: 22,
                  label: '二级子公司11',
                }
              ]
            },
            {
              id: 12,
              label: '一级子公司2'
            }
          ]
        }
      ],
      // 当获取到的数据与这里的字段不相符时,可以进行相应的对应设置
      defaultProps: {
        id: 'id',
        label: 'label',
        children: 'children'
      },
      filterText:''
    }
  },

  watch:{
    filterText(val){
      this.$refs.tree.filter(val)
    }
  },

  methods:{
    filterNode(value,data){
      if(!value) return true
      return data.label.indexOf(value) !== -1
    }
  }
}
script>

<style lang="scss" scoped>
.el-tree /deep/ .el-tree__empty-block {
  width: 200px;
}

.el-tree /deep/ .el-tree-node > .el-tree-node__content {
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: #666666;
}

.el-tree /deep/ .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f8ff !important;
  color: #017cd9 !important;
}
style>

el-tree和el-table相关使用_第1张图片
el-tree和el-table相关使用_第2张图片

el-tree实现node节点增删改

<template>
  <div class="app-container">
    <el-tree
      :data="epTree"
      default-expand-all
      :props="defaultProps"
      :expand-on-click-node="false"
      :render-content="renderContent"
    >el-tree>

    <el-dialog
      title="新增"
      :visible.sync="addDialog"
      width="30%"
      :before-close="handleAddClose"
      :modal-append-to-body="false"
    >
      <span>node信息:span>
      <div>{{nodeInfo}}div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消el-button>
        <el-button type="primary" @click="addDialog = false">确 定el-button>
      span>
    el-dialog>

    <el-dialog
      title="修改"
      :visible.sync="editDialog"
      width="30%"
      :before-close="handleEditClose"
      :modal-append-to-body="false"
    >
      <span>node信息:span>
      <div>{{nodeInfo}}div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消el-button>
        <el-button type="primary" @click="editDialog = false">确 定el-button>
      span>
    el-dialog>
  div>
template>

<script>
export default {
  data() {
    return {
      epTree: [
        {
          id: 1,
          label: '一级公司',
          children: [
            {
              id: 11,
              label: '一级子公司1',
              children: [
                {
                  id: 22,
                  label: '二级子公司11',
                }
              ]
            },
            {
              id: 12,
              label: '一级子公司2'
            }
          ]
        }
      ],
      // 当获取到的数据与这里的字段不相符时,可以进行相应的对应设置
      defaultProps: {
        id: 'id',
        label: 'label',
        children: 'children'
      },
      addDialog: false,
      editDialog:false,
      nodeInfo:[]
    }
  },

  methods: {
    renderContent(h, { node, data, store }) {
      return (
        <div style="width:100%;">
          <span style="margin-right:10px;">{node.label}</span>
          <span><i on-click={() => this.append(data)} class="el-icon-plus" title="添加"></i></span>
          <span style="margin-left:8px;"><i on-click={() => this.update(data)} class="el-icon-edit" title="修改"></i></span>
          <span style="margin-left:8px;"><i on-click={() => this.delete(data)} class="el-icon-delete" title="删除"></i></span>
        </div>
      )
    },

    append(data) {
      this.addDialog = true
      this.nodeInfo = data
    },
    update(data) { 
      this.editDialog = true
      this.nodeInfo = data
    },
    delete(data) {
      this.$confirm('是否删除选中的节点?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 请求删除节点api
        console.log(data);
      }).catch(err => console.log(err))
    },

    handleAddClose() {
      this.addDialog = false
    },

    handleEditClose(){
      this.editDialog = false
    }
  }
}
script>

<style lang="scss" scoped>
.el-tree /deep/ .el-tree__empty-block {
  width: 200px;
}

.el-tree /deep/ .el-tree-node > .el-tree-node__content {
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: #666666;
}

.el-tree /deep/ .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f8ff !important;
  color: #017cd9 !important;
}
style>

el-tree和el-table相关使用_第3张图片
el-tree和el-table相关使用_第4张图片
el-tree和el-table相关使用_第5张图片
el-tree和el-table相关使用_第6张图片

el-tree 实现节点懒加载

<template>
  <div class="app-container">
    <el-tree
      :data="epTree"
      :props="defaultProps"
      :load="loadNode"
      lazy
      @check-change="handleCheckChange"
    >
    el-tree>
  div>
template>

<script>
export default {
  data () {
    return {
      epTree: [
        {
          id: 1,
          label: '一级公司',
          children: [
            {
              id: 11,
              label: '一级子公司1',
              children: [
                {
                  id: 22,
                  label: '二级子公司11',
                }
              ]
            },
            {
              id: 12,
              label: '一级子公司2'
            }
          ]
        }
      ],
      // 当获取到的数据与这里的字段不相符时,可以进行相应的对应设置
      defaultProps: {
        id: 'id',
        label: 'label',
        children: 'children'
      },
      // 带根节点的情况
      // rootNode: {
      //   'id': '0',
      //   'label': '所属企业分类树'
      // }
    }
  },

  methods: {
    // 带根节点的情况
    // loadNode (node, resolve) {
    //   let self = this
    //   if (node.level === 0) {
    //     console.log('第一次加载根节点');
    //     return resolve([self.rootNode])
    //   } else {
    //     console.log('加载子节点');
    //     // 加载树形结构数据
    //     // let params = {
    //     //   userId:2,
    //     //   pcode:node.id
    //     // }
    //     // fetchEpTreeData(params).then(res => {
    //     //   if(res.code === 0){
    //     //     let epTree = res.data
    //     //   }
    //     // }).catch(err => console.log(err))
    //     let epTree = this.epTree
    //     console.log('返回列表', epTree);
    //     resolve(epTree)
    //   }
    // },

    // 不带根节点
    loadNode (node, resolve) {
      // 加载树形结构数据
      // let params = {
      //   userId:2,
      //   pcode:node.id ? node.id : ''
      // }
      // fetchEpTreeData(params).then(res => {
      //   if(res.code === 0){
      //     let epTree = res.data
      //   }
      // }).catch(err => console.log(err))

      let epTree = this.epTree
      resolve(epTree)
    },

    handleCheckChange (value) {
      console.log(value);
    }
  }
}
script>

<style lang="scss" scoped>
.el-tree /deep/ .el-tree__empty-block {
  width: 200px;
}

.el-tree /deep/ .el-tree-node > .el-tree-node__content {
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: #666666;
}

.el-tree /deep/ .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f8ff !important;
  color: #017cd9 !important;
}
style>

在这里插入图片描述
在这里插入图片描述

el-tree获取所有选中的当前节点

<template>
  <div class="app-container">
    <el-tree
      node-key="id"
      :data="epTree"
      show-checkbox
      check-strictly
      :props="defaultProps"
      default-expand-all
      @check-change="handleCheckChange"
    >
    el-tree>
    {{selectedKeys}}
  div>
template>

<script>
export default {
  data () {
    return {
      epTree: [
        {
          id: 1,
          label: '一级公司',
          children: [
            {
              id: 11,
              label: '一级子公司1',
              children: [
                {
                  id: 22,
                  label: '二级子公司11',
                }
              ]
            },
            {
              id: 12,
              label: '一级子公司2'
            }
          ]
        }
      ],
      // 当获取到的数据与这里的字段不相符时,可以进行相应的对应设置
      defaultProps: {
        id: 'id',
        label: 'label',
        children: 'children'
      },
      selectedKeys:[]
    }
  },

  methods: {
    handleCheckChange (value) {
      if(!this.selectedKeys.includes(value.id)){
        this.selectedKeys.push(value.id)
      }else{
        this.selectedKeys = this.selectedKeys.filter(item => item !== value.id)
      }
    }
  }
}
script>

<style lang="scss" scoped>
.el-tree /deep/ .el-tree__empty-block {
  width: 200px;
}

.el-tree /deep/ .el-tree-node > .el-tree-node__content {
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: #666666;
}

.el-tree /deep/ .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f8ff !important;
  color: #017cd9 !important;
}
style>

el-tree和el-table相关使用_第7张图片

el-tree获取当前节点及其选中父节点

<template>
  <div class="app-container">
    <el-tree
      node-key="id"
      :data="epTree"
      show-checkbox
      :props="defaultProps"
      default-expand-all
      ref="treeRef"
    >
    el-tree>
    <el-button type="primary" @click="getSelectedKeys"
      >获取选中节点及其父节点el-button
    >
    {{ selectedKeys }}
  div>
template>

<script>
export default {
  data () {
    return {
      epTree: [
        {
          id: 1,
          label: '一级公司',
          children: [
            {
              id: 11,
              label: '一级子公司1',
              children: [
                {
                  id: 22,
                  label: '二级子公司11',
                }
              ]
            },
            {
              id: 12,
              label: '一级子公司2'
            }
          ]
        }
      ],
      // 当获取到的数据与这里的字段不相符时,可以进行相应的对应设置
      defaultProps: {
        id: 'id',
        label: 'label',
        children: 'children'
      },
      selectedKeys: []
    }
  },

  methods: {
    getSelectedKeys () {
      this.selectedKeys = this.getCheckedKeys(this.epTree, this.$refs.treeRef.getCheckedKeys(), 'id')
    },

    getCheckedKeys (data, keys, key) {
      var res = []
      recursion(data, false);
      return res

      function recursion (arr, isChild) {
        var aCheck = []
        for (let i = 0; i < arr.length; i++) {
          var obj = arr[i]
          aCheck[i] = false
          if (obj.children) {
            aCheck[i] = recursion(obj.children, true) ? true : aCheck[i]
            if (aCheck[i]) {
              res.push(obj[key])
            }
          }

          for (var j = 0; j < keys.length; j++) {
            if (obj[key] == keys[j]) {
              aCheck[i] = true;
              if (res.indexOf(obj[key]) == -1) {
                res.push(obj[key]);
              }
              break;
            }
          }
        }
        if (isChild) {
          return aCheck.indexOf(true) != -1;
        }
      }
    }
  }
}
script>

<style lang="scss" scoped>
.el-tree /deep/ .el-tree__empty-block {
  width: 200px;
}

.el-tree /deep/ .el-tree-node > .el-tree-node__content {
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: #666666;
}

.el-tree /deep/ .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f8ff !important;
  color: #017cd9 !important;
}
style>

el-tree和el-table相关使用_第8张图片

el-table 获取多选行的所有节点

<template>
  <div class="app-container">
    {{multipleSelections}}
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55">el-table-column>
      <el-table-column type="index" label="#">el-table-column>
      <el-table-column prop="label" label="展示">el-table-column>
    el-table>
  div>
template>

<script>
export default {
  data () {
    return {
      tableData:[
        {
          id:1,
          label:'展示1'
        },
        {
          id:2,
          label:'展示2'
        },
        {
          id:3,
          label:'展示3'
        },
        {
          id:4,
          label:'展示4'
        },
        {
          id:5,
          label:'展示5'
        }
      ],
      multipleSelections:[]
    }
  },

  methods: {
    handleSelectionChange(val){
      this.multipleSelections = []
      val.length > 0 && val.forEach(item => {
        this.multipleSelections.push(item.id)
      });
    }
  }
}
script>

el-tree和el-table相关使用_第9张图片

el-table 动态添加删除行数据

<template>
  <div class="app-container">
    <el-table
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{
        background: '#3d80f2',
        color: '#fff',
        fontSize: '14px',
        height: '40px',
      }"
    >
      <el-table-column
        prop="numbering"
        label="编号"
        align="center"
      >el-table-column>
      <el-table-column prop="title" label="标题" align="center">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.title"
            placeholder="请输入"
          >el-input>
        template>
      el-table-column>
      <el-table-column prop="type" label="类型" align="center">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.type"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >el-option>
          el-select>
        template>
      el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status">el-switch>
        template>
      el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="addClick">新增el-button>
          <el-button
            type="text"
            style="color:red;"
            @click="handleDelete(scope.$index, scope.row)"
            >删除el-button
          >
        template>
      el-table-column>
    el-table>
  div>
template>

<script>
export default {
  data () {
    return {
      tableData: [
        {
          numbering: "编号-1",
          title: "",
          type:null,
          status:true,
        }
      ],
      options:[
        {
          id:1,
          label:'类型1'
        },{
          id:2,
          label:'类型2'
        },{
          id:3,
          label:'类型3'
        }
      ]
    }
  },

  methods: {
    //新增方法
    addClick () {
      this.valNumer = this.valNumer + 1;
      var list = {
        numbering: "编号" + `-${this.tableData.length + 1}`,
        title: this.title,
        type:this.type,
        status:this.status
      };
      this.tableData.push(list);
    },
    //删除新增的某行数据
    handleDelete (index, row) {
      this.tableData.splice(index, 1);
      for (var i = index; i < this.tableData.length; i++) {//从某一行删除了编号,删除的编号后面的编号数据要依次减一,所以遍历删除编号后面的数据
        this.tableData[i].numbering = "编号" + `-${Number(this.tableData[i].numbering.split("-")[1]) - 1}`;
      }
    }
  }
};
script>

<style lang="scss" scoped>
.dialogDiv {
  height: 300px;
  overflow: auto;
}
style>

el-tree和el-table相关使用_第10张图片

vue+element ui实现table表格行的上下移动

<template>
  <div class="app-container">
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column type="index" label="#">el-table-column>
      <el-table-column prop="date" label="日期" width="180"> el-table-column>
      <el-table-column prop="name" label="姓名" width="180"> el-table-column>
      <el-table-column prop="address" label="地址"> el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            :disabled="scope.$index === 0"
            @click="moveUp(scope.$index, scope.row)"
            ><i class="el-icon-arrow-up">i
          >el-button>
          <el-button
            size="mini"
            type="text"
            :disabled="scope.$index === tableData.length - 1"
            @click="moveDown(scope.$index, scope.row)"
            ><i class="el-icon-arrow-down">i
          >el-button>
        template>
      el-table-column>
    el-table>
  div>
template>

<script>
export default {
  data () {
    return {
      tableData: [{
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄'
      }, {
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄'
      }, {
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄'
      }]
    }
  },

  methods: {
    //上移
    moveUp (index, row) {
      var that = this;
      if (index > 0) {
        let upDate = that.tableData[index - 1];
        that.tableData.splice(index - 1, 1);
        that.tableData.splice(index, 0, upDate);
      } else {
        alert('已经是第一条,不可上移');
      }
    },

    //下移
    moveDown (index, row) {
      var that = this;
      if ((index + 1) === that.tableData.length) {
        alert('已经是最后一条,不可下移');
      } else {
        let downDate = that.tableData[index + 1];
        that.tableData.splice(index + 1, 1);
        that.tableData.splice(index, 0, downDate);
      }
    }
  }
}
script>

el-tree和el-table相关使用_第11张图片

el-table动态添加实现元素校验

<template>
  <div class="app-container">
    <el-form ref="form" :model="tableObj">
      <el-table
        :data="tableObj.tableData"
        style="width: 100%"
        :header-cell-style="{
          background: '#3d80f2',
          color: '#fff',
          fontSize: '14px',
          height: '40px',
        }"
      >
        <el-table-column
          prop="numbering"
          label="编号"
          align="center"
        >el-table-column>
        <el-table-column prop="title" label="标题" align="center">
          <template slot-scope="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.title'"
              :rules="rules.title"
            >
              <el-input
                v-model="scope.row.title"
                placeholder="请输入"
              >el-input>
            el-form-item>
          template>
        el-table-column>
        <el-table-column prop="title" label="数量" align="center">
          <template slot-scope="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.number'"
              :rules="rules.number"
            >
              <el-input
                v-model="scope.row.number"
                type="number"
                placeholder="请输入"
              >el-input>
            el-form-item>
          template>
        el-table-column>
        <el-table-column prop="type" label="类型" align="center">
          <template slot-scope="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.type'"
              :rules="rules.type"
            >
              <el-select
                v-model="scope.row.type"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                >el-option>
              el-select>
            el-form-item>
          template>
        el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status">el-switch>
          template>
        el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="addClick">新增el-button>
            <el-button
              type="text"
              style="color: red"
              @click="handleDelete(scope.$index, scope.row)"
              >删除el-button
            >
          template>
        el-table-column>
      el-table>
    el-form>

    <div style="text-align: center; margin-top: 20px">
      <el-button type="primary" size="mini" @click="handleSubmit"
        >提交el-button
      >
    div>
  div>
template>

<script>
export default {
  data () {
    return {
      tableObj: {
        tableData: [
          {
            numbering: "编号-1",
            title: "",
            number: '',
            type: '',
            status: true,
          }
        ]
      },
      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        number: [{ required: true, message: "数量不能为空", trigger: "blur" }],
        type: [{ required: true, message: "类型不能为空", trigger: "blur" }]
      },
      options: [
        {
          id: 1,
          label: '类型1'
        }, {
          id: 2,
          label: '类型2'
        }, {
          id: 3,
          label: '类型3'
        }
      ]
    }
  },

  methods: {
    //新增方法
    addClick () {
      this.valNumer = this.valNumer + 1;
      var list = {
        numbering: "编号" + `-${this.tableObj.tableData.length + 1}`,
        title: this.title,
        type: this.type,
        status: this.status
      };
      this.tableObj.tableData.push(list);
    },
    //删除新增的某行数据
    handleDelete (index, row) {
      this.tableObj.tableData.splice(index, 1);
      for (var i = index; i < this.tableObj.tableData.length; i++) {//从某一行删除了编号,删除的编号后面的编号数据要依次减一,所以遍历删除编号后面的数据
        this.tableObj.tableData[i].numbering = "编号" + `-${Number(this.tableObj.tableData[i].numbering.split("-")[1]) - 1}`;
      }
    },

    handleSubmit () {
      console.log('submit');
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log('valid');
        }
      })
    }
  }
};
script>

<style lang="scss" scoped>
.dialogDiv {
  height: 300px;
  overflow: auto;
}
style>

el-tree和el-table相关使用_第12张图片

el-tree通过条件控制节点的操作

<template>
  <div class="app-container">
    <el-tree
      :data="epTree"
      default-expand-all
      :props="defaultProps"
      :expand-on-click-node="false"
      :render-content="renderContent"
    >el-tree>

    <el-dialog
      title="新增"
      :visible.sync="addDialog"
      width="30%"
      :before-close="handleAddClose"
      :modal-append-to-body="false"
    >
      <span>node信息:span>
      <div>{{nodeInfo}}div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消el-button>
        <el-button type="primary" @click="addDialog = false">确 定el-button>
      span>
    el-dialog>

    <el-dialog
      title="修改"
      :visible.sync="editDialog"
      width="30%"
      :before-close="handleEditClose"
      :modal-append-to-body="false"
    >
      <span>node信息:span>
      <div>{{nodeInfo}}div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消el-button>
        <el-button type="primary" @click="editDialog = false">确 定el-button>
      span>
    el-dialog>
  div>
template>

<script>
export default {
  data() {
    return {
      /**
       * flag=1 新增、删除
       * flag=2 修改、删除
       * flag=3 修改
       */
      epTree: [
        {
          id: 1,
          label: '一级公司',
          flag:1,
          children: [
            {
              id: 11,
              label: '一级子公司1',
              flag:2,
              children: [
                {
                  id: 22,
                  label: '二级子公司11',
                  flag:1
                }
              ]
            },
            {
              id: 12,
              label: '一级子公司2',
              flag:3
            }
          ]
        }
      ],
      // 当获取到的数据与这里的字段不相符时,可以进行相应的对应设置
      defaultProps: {
        id: 'id',
        label: 'label',
        children: 'children'
      },
      addDialog: false,
      editDialog:false,
      nodeInfo:[]
    }
  },

  methods: {
    renderContent(h, { node, data, store }) {
      return (
        <div style="width:100%;">
          <span style="margin-right:10px;">{node.label}</span>
          {
            data.flag === 1 ? <span><i on-click={() => this.append(data)} class="el-icon-plus" title="添加"></i></span> : ''
          }

          {
            (data.flag === 2 || data.flag === 3) ? <span style="margin-left:8px;"><i on-click={() => this.update(data)} class="el-icon-edit" title="修改"></i></span> : ''
          }

          {
            (data.flag === 1 || data.flag === 2) ? <span style="margin-left:8px;"><i on-click={() => this.delete(data)} class="el-icon-delete" title="删除"></i></span> : ''
          }
        </div>
      )
    },

    append(data) {
      this.addDialog = true
      this.nodeInfo = data
    },
    update(data) { 
      this.editDialog = true
      this.nodeInfo = data
    },
    delete(data) {
      this.$confirm('是否删除选中的节点?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 请求删除节点api
        console.log(data);
      }).catch(err => console.log(err))
    },

    handleAddClose() {
      this.addDialog = false
    },

    handleEditClose(){
      this.editDialog = false
    }
  }
}
script>

<style lang="scss" scoped>
.el-tree /deep/ .el-tree__empty-block {
  width: 200px;
}

.el-tree /deep/ .el-tree-node > .el-tree-node__content {
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: #666666;
}

.el-tree /deep/ .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f8ff !important;
  color: #017cd9 !important;
}
style>

el-tree和el-table相关使用_第13张图片

el-table 实现动态拖拽

<template>
  <div class="draggable" style="padding: 20px">
    <el-table row-key="id" :data="tableData" style="width: 100%" border>
      <el-table-column
        v-for="(item, index) in oldList"
        :key="`col_${index}`"
        :prop="newList[index].prop"
        :label="item.label"
        align="center"
      >
      el-table-column>
    el-table>
  div>
template>
<script>
import Sortable from 'sortablejs';

export default {
  mounted () {
    this.oldList = JSON.parse(JSON.stringify(this.tableConfig.tableItems))
    this.newList = JSON.parse(JSON.stringify(this.tableConfig.tableItems))
    this.columnDrop()
    this.rowDrop()
  },
  data () {
    return {
      oldList: [],
      newList: [],
      tableData: [
        {
          id: 1,
          name: '李一',
          gender: '男',
          age: 30,
          job: "会计"
        },
        {
          id: 2,
          name: '王二',
          gender: '未知',
          age: 18,
          job: "无业游民"
        },
        {
          id: 3,
          name: '张三',
          gender: '男',
          age: 50,
          job: "老板"
        },
      ],
      tableConfig: {
        tableItems: [
          {
            label: '序号',
            prop: 'id'
          },
          {
            label: '姓名',
            prop: 'name',
          },
          {
            label: '性别',
            prop: 'gender',
          },
          {
            label: '年龄',
            prop: 'age',
          },
          {
            label: '工作',
            prop: 'job',
          },
        ]
      }
    }
  },
  methods: {
    // 行拖拽
    rowDrop () {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.draggable .el-table__body-wrapper tbody');
      const _this = this;
      Sortable.create(tbody, {
        //  指定父元素下可被拖拽的子元素
        draggable: ".draggable .el-table__row",
        onEnd ({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0];
          _this.tableData.splice(newIndex, 0, currRow);
        }
      });
    },
    // 列拖拽
    columnDrop () {
      const wrapperTr = document.querySelector('.draggable .el-table__header-wrapper tr');
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: evt => {
          const oldItem = this.newList[evt.oldIndex];
          this.newList.splice(evt.oldIndex, 1);
          this.newList.splice(evt.newIndex, 0, oldItem);
        }
      });
    }
  }
}
script>
<style scoped>
style>

el-tree和el-table相关使用_第14张图片

el-form 实现动态添加并实现校验

<template>
  <div class="app-container">
    <el-form :model="environmentForm" ref="environmentForm">
      <el-row
        :gutter="10"
        v-for="(item, index) in environmentForm.items"
        :key="item.key"
      >
        <el-col :span="6">
          <el-form-item
            label="名称"
            :prop="'items.' + index + '.name'"
            :rules="rules.name"
          >
            <el-input v-model="item.name">el-input>
          el-form-item>
        el-col>
        <el-col :span="6">
          <el-form-item
            label="变量"
            :prop="'items.' + index + '.variable'"
            :rules="rules.variable"
          >
            <el-input v-model="item.variable">el-input>
          el-form-item>
        el-col>
        <el-col :span="6">
          <el-form-item
            label="描述"
            :prop="'items.' + index + '.description'"
            :rules="rules.description"
          >
            <el-input v-model="item.description">el-input>
          el-form-item>
        el-col>
        <el-col :span="3" v-if="environmentForm.items.length !== 1" style="padding:40px;">
          <el-button type="text" style="color: red" @click="removeEnvironmentForm(item)"
            >删除el-button
          >
        el-col>
        <el-col :span="3" style="padding:40px;">
          <el-button
            type="text"
            @click="addEnvironmentForm"
          >添加el-button>
        el-col>
      el-row>

      <el-form-item>
        <el-button type="primary" @click="submitForm('environmentForm')"
          >提交el-button
        >
        <el-button @click="resetForm('environmentForm')">重置el-button>
      el-form-item>
    el-form>
  div>
template>

<script>
export default {
  data () {
    return {
      environmentForm: {
        items: [{
          name: '',
          variable: '',
          description: ''
        }]
      },

      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        variable: [{ required: true, message: '变量不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
      }
    }
  },
  methods: {
    //提交事件
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('提交', this.environmentForm);
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //重置事件
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
    //移除表单项事件
    removeEnvironmentForm (item) {
      var index = this.environmentForm.items.indexOf(item)
      if (index !== -1) {
        this.environmentForm.items.splice(index, 1)
      }
    },
    //添加表单项事件
    addEnvironmentForm () {
      this.environmentForm.items.push({
        name: '',
        variable: '',
        description: '',
        key: Date.now()
      });
    }
  }
}
script>

el-tree和el-table相关使用_第15张图片

el-table 动态增行通过dialog操作并将数据回显到table中

<template>
  <div class="app-container">
    <el-table
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{
        background: '#3d80f2',
        color: '#fff',
        fontSize: '14px',
        height: '40px',
      }"
    >
      <el-table-column
        prop="numbering"
        label="编号"
        align="center"
      >el-table-column>
      <el-table-column prop="title" label="标题" align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.title" placeholder="请输入">el-input>
        template>
      el-table-column>
      <el-table-column prop="type" label="类型" align="center">
        <template slot-scope="scope">
          <el-select v-model="scope.row.type" placeholder="请选择" clearable>
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >el-option>
          el-select>
        template>
      el-table-column>
      <el-table-column prop="sortName" label="分类" align="center">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.sortName"
            placeholder="分类"
            @focus="handleFocus(scope.$index,scope.row)"
          >el-input>
        template>
      el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status">el-switch>
        template>
      el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="addClick">新增el-button>
          <el-button
            type="text"
            style="color: red"
            @click="handleDelete(scope.$index, scope.row)"
            >删除el-button
          >
        template>
      el-table-column>
    el-table>

    <el-dialog
      title="分类选择"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
      append-to-body
    >
    <div>
      <h3>请选择分类:h3>
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="item in orderList"
            :key="item.id"
            :label="item.id"
            >{{ item.label }}el-checkbox
          >
        el-checkbox-group>
    div>

    <div>
      <h3>所属分类为:h3>
      <span v-for="(item, index) in checkList" :key="index">{{orderObj[item]}}  span>
    div>
       
      <span slot="footer" class="dialog-footer">
        <el-button type="text" @click="handleClose">取 消el-button>
        <el-button type="primary" size="mini" @click="handleSubmit"
          >确 定el-button
        >
      span>
    el-dialog>
  div>
template>

<script>
export default {
  data () {
    return {
      tableData: [
        {
          numbering: "编号-1",
          title: "",
          type: '',
          sortName: '',
          sortList: '',
          status: true,
        }
      ],
      options: [
        {
          id: 1,
          label: '类型1'
        }, {
          id: 2,
          label: '类型2'
        }, {
          id: 3,
          label: '类型3'
        }
      ],
      dialogVisible:false,
      index:null,
      checkList:[],
      checkOrder:[],
      orderList:[
        {
          id:0,
          label:'shopping'
        },
        {
          id:1,
          label:'singing'
        },
        {
          id:2,
          label:'cooking'
        },
        {
          id:3,
          label:'dancing'
        },
        {
          id:4,
          label:'reading'
        }
      ],
      orderObj:['shopping','singing','cooking','dancing','reading'],
      checkAllList:[]
    }
  },

  methods: {
    handleFocus (index,row) {
      this.index = index
      this.dialogVisible = true

      if (this.checkAllList[this.index] === undefined) {
        this.checkList = []
      } else {
        this.checkList = this.checkAllList[this.index]
      }
    },

    handleClose(){
      this.checkOrder = []
      this.dialogVisible = false
    },

    handleSubmit(){
      console.log('submit');
      this.checkList.forEach(item => {
        this.checkOrder.push(this.orderObj[item])
      })

      this.checkAllList[this.index] = this.checkList
      this.tableData[this.index].sortList = this.checkList.join(',')
      this.tableData[this.index].sortName = this.checkOrder.join(',') 
      this.dialogVisible = false
      this.checkOrder = []
    },

    //新增方法
    addClick () {
      this.valNumer = this.valNumer + 1;
      var list = {
        numbering: "编号" + `-${this.tableData.length + 1}`,
        title: this.title,
        type: this.type,
        sortName: this.sortName,
        sortList: this.sortList,
        status: this.status
      };
      this.tableData.push(list);
    },
    //删除新增的某行数据
    handleDelete (index, row) {
      this.tableData.splice(index, 1);
      for (var i = index; i < this.tableData.length; i++) {//从某一行删除了编号,删除的编号后面的编号数据要依次减一,所以遍历删除编号后面的数据
        this.tableData[i].numbering = "编号" + `-${Number(this.tableData[i].numbering.split("-")[1]) - 1}`;
      }
    }
  }
};
script>

<style lang="scss" scoped>
.dialogDiv {
  height: 300px;
  overflow: auto;
}

.el-checkbox{
  margin: 0 10px 5px 10px;
}
style>

el-tree和el-table相关使用_第16张图片
el-tree和el-table相关使用_第17张图片

v3实现table行的可选择展开

el-tree和el-table相关使用_第18张图片

 <el-table :data="roleList" :row-class-name="getRowClass" border>
  <el-table-column type="expand">
        <template #default="props">
        template>
      el-table-column>
 el-table>
const getRowClass = ({ row, rowIndex }) => {
  if (row.children.length == 0) {
    return 'row-expand-cover'
  }
}
/* css样式注意不要在scoped中修改;为了避免污染,最好利用deep穿透 */

你可能感兴趣的:(vue,vue.js,node.js,javascript)