el-tree和el-table相关使用

2023-11-16

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实现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 实现节点懒加载

<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获取当前节点及其选中父节点

<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-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-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>

在这里插入图片描述

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-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通过条件控制节点的操作

<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-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-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-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>

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

v3实现table行的可选择展开

在这里插入图片描述

 <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穿透 */
<style>
/* .row-expand-cover .el-table__expand-column .cell {
  display: none;
} */

.row-expand-cover .el-table__expand-column .el-icon {
  visibility: hidden;
}
</style>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

el-tree和el-table相关使用 的相关文章

  • 如何在ASP.NET Webform中使用Jquery表单插件?

    我遇到了这个插件 http malsup com jquery form getting started http malsup com jquery form getting started 我想知道如何在 ASP NET WebForm
  • 如何使用 JavaScript 中的值填充下拉列表?

    我在 Tridion CMS 扩展中的功能区工具栏按钮中添加了一个按钮 单击该按钮后 将显示一个弹出页面 其中包含两个下拉菜单 通过更改第一个下拉控件中的值 我应该填充第二个下拉控件的值 就我而言 我正在使用ASP drop down li
  • 在Javascript中按降序对字符串进行排序(最有效)?

    W3Schools 有这个例子 var fruits Banana Orange Apple Mango fruits sort fruits reverse 这是在 Javascript 中按降序对字符串进行排序的最有效方法吗 Updat
  • jQuery 选择 # id 以单词为前缀,计数器为后缀

    有没有办法用 jQuery 选择所有带有前缀 my 和后缀 0 9 的 id 像这样的 my 1 4 还是可以用循环来实现 div div div div div div div div div div 第一个想法 似乎效果很好 div i
  • 如何按照编写的顺序迭代 javascript 对象属性

    我发现了代码中的一个错误 我希望通过最少的重构工作来解决该错误 此错误发生在 Chrome 和 Opera 浏览器中 问题 var obj 23 AA 12 BB iterating through obj s properties for
  • 检查 touchend 是否在拖动后出现

    我有一些代码可以更改表的类 在手机上 有时表格对于屏幕来说太宽 用户将拖动 滚动来查看内容 但是 当他们触摸并拖动表格时 每次拖动都会触发 touchend 如何测试触摸端是否是触摸拖动的结果 我尝试跟踪dragstart和dragend
  • 如何检查请求是否通过 Express 中的 https 发送

    我想强制某些路线始终在我的 Express 应用程序中使用安全连接 我如何检查以确保它使用 https 我在 heroku 上使用搭载 ssl 进行部署 我也在 Heroku 上部署 当他们使用 nginx 进行反向代理时 他们添加了一堆标
  • 如果链接包含特定文本,jQuery 将类添加到 href

    我的网站上的列表中有一些动态填充的链接 这些链接链接到文件 是否可以使用 jQuery 查看文件名是否以 pdf 结尾 并在 href 或类似的链接文本以 mp3 结尾时添加一个类 例如 我的列表中有以下链接 文件1 pdf 歌曲1 mp3
  • Cloudfoundry:如何组合两个运行时

    cloundfoundry 有没有办法结合两个运行时环境 我正在将 NodeJS 应用程序部署到 IBM Bluemix 现在 我还希望能够执行独立的 jar 文件 但应用程序失败 APP 0 bin sh 1 java not found
  • 如何流式传输 OpenAI 的完成 API?

    我想流式传输结果通过 OpenAI 的 API 完成 https beta openai com docs api reference completions 该文档提到使用服务器发送的事件 https developer mozilla
  • 是否有任何非轮询方式来检测 DOM 元素的大小或位置何时发生变化?

    很长一段时间以来 我一直在寻找一种方法来检测 DOM 元素的大小或位置何时发生变化 这可能是因为窗口调整了大小 或者因为向该元素添加了新的子元素 或者因为在该元素周围添加了新元素 或者因为 CSS 规则已更改 或者因为用户更改了浏览器的字体
  • 如何在 Angular 中从父组件访问子组件?

    I have mat paginator在子组件a中 如下所示 子组件 html
  • 将数组排序为第一个最小值、第一个最大值、第二个最小值、第二个最大值等

    编写一个JS程序 返回一个数组 其中第一个元素是第一个最小值 第二个元素是第一个最大值 依此类推 该程序包含一个函数 该函数接受一个参数 一个数组 该函数根据要求返回数组 输入示例 array 2 4 7 1 3 8 9 预期输出 1 9
  • 查询为空 Node Js Sequelize

    我正在尝试更新 Node js 应用程序中的数据 我和邮递员测试过 我的开发步骤是 从数据库 MySQL 获取ID为10的数据进行更新 gt gt 未处理的拒绝SequelizeDatabaseError 查询为空 我认识到 我使用了错误的
  • 当用户单击链接时,如何记录 MixPanel 事件?

    当用户单击某种类型的链接时 我试图在 MixPanel 中记录一个事件 我正在使用 JQuery 不引人注意地完成此操作 据我所知 我需要添加一个回调函数 以便在记录事件后将用户带到 URL 这是我正在使用的代码 不幸的是
  • Jquery - 通过在字符串中构建 id 的 id 获取元素

    我在使用 jquery 元素时遇到问题 我正在 var 中构造名称 例如 var myId myGotId myId attr title changed myId 返回空 我想通过 id 获取我的元素 但动态构建我的 Id 连接字符串 编
  • 单击引导分页链接时调用 jquery 函数

    我想在单击引导分页链接时调用 jquery 函数 假设我想从第1页遍历到第2页 应该调用一个jquery函数 我正在使用以下代码 但它不起作用 ul pagination on click li function alert page ch
  • 如何在 gulp.src 中使用基本正则表达式?

    我正在尝试选择两个文件gulp src highcharts js and highcharts src js 当然 我知道我可以使用数组表达式显式添加这两个表达式 但出于学习目的 我尝试为它们编写一个表达式 我读过可以使用简单的正则表达式
  • 如何使用 Passport 验证 Supertest 请求?

    我使用 Passport js 进行身份验证 本地策略 并使用 Mocha 和 Supertest 进行测试 如何使用 Supertest 创建会话并发出经过身份验证的请求 正如 zeMirco 指出的那样 底层superagent模块支持
  • 用于 C# XNA 的 Javascript(或类似)游戏脚本

    最近我准备用 XNA C 开发另一个游戏 上次我在 XNA C 中开发游戏时 遇到了必须向游戏中添加地图和可自定义数据的问题 每次我想添加新内容或更改游戏角色的某些值或其他内容时 我都必须重建整个游戏或其他内容 这可能需要相当长的时间 有没

随机推荐

  • 【机器学习】人工神经网络(ANN)浅讲

    神经网络是一门重要的机器学习技术 它是目前最为火热的研究方向 深度学习的基础 学习神经网络不仅可以让你掌握一门强大的机器学习方法 同时也可以更好地帮助你理解深度学习技术 本文以一种简单的 循序的方式讲解神经网络 适合对神经网络了解不多的同学
  • Layui富文本编辑器图片上传接口(.NET C#)

    本来想偷懒找个现成的接口 搜了一下发现没有现成的 那我在这写一个并分享给大家吧 demo打包好了在我的csdn下载中心 http download csdn net download xianglikai1 9970000 下面也有代码和结
  • 设置QListWidget背景色为透明

    只要一条指令就可以实现 ui gt listWidget gt setStyleSheet background color transparent 其中background color设置参考CSS背景设置如下 以下摘自 http www
  • PD通信协议芯片选型分析对比

    目录 一 PD SINK协议芯片对比图 二 总结 关键词 pd协议芯片 协议芯片 芯片通信协议 通信协议 前言 在如今快节奏生活不断蔓延的背景下 人们对各种事情的处理也渐渐地开始要求在保证质量的情况下 不断加快 手机快充就是一个典型的例子
  • iOS开发之Xcode 6更新默认不支持armv7s架构

    最近一次的Xcode 6更新默认不再支持arm7s架构 究竟是要废除不用呢还是仅仅只是一个疏忽 目前的Xcode 6配置里定义 ARCHS STANDARD 为armv7 arm64 当然这个定义前提是它会一再要求你删除掉你原本设定的构建架
  • 将对象的null字段赋值为默认值

    import java lang reflect Field import java math BigDecimal import java util ArrayList import java util Date import org a
  • 【Redis详细教程】Linux下如何安装Redis

    第一步 下载 redis wget https download redis io releases redis 6 2 6 tar gz 第二步 解压 redis 6 2 6 tar gz 并将其重新命名为 redis tar xvf r
  • 前端实现:点击硬币实现硬币翻转动画,且动画停止时正反面随机

    html div class pic box div class boxes div class box 硬币正面图片 img alt 硬币反面图片 img div div div
  • 基于Spring Boot + Vue的智慧宿舍管理系统设计与实现

    Java全能学习 面试指南 https javaxiaobear cn 摘要 随着智能化技术的快速发展 智慧宿舍管理系统在大学校园中得到了广泛的应用 本论文旨在设计并实现一种基于前后端分离的智慧宿舍管理系统 通过将前端和后端进行分离 提高系
  • windows安装minio

    官网下载地址 https min io download windows 进入minio exe的目录执行启动命令 minio exe server C Users wwwch Desktop minio data C Users wwwc
  • 基于循环神经网络的图像特定文本抽取方法

    作者的模型整体框架包含两部分 分别为 OCR 部分 采用人家的模型 输出文本 特定文本抽取部分 作者的工作 1 引言 早期图像特定文本抽取主要是通过 OCR 中的版面分析 Layout analysis 来实现 即首先利用 版面分析 的方法
  • Python+django的ORM查询

    在使用python后端开发时 很多人都会遇到使用原生sql还是django自带的orm进行数据库的操作好呢 纠结的原因有很多 其中一点就是对orm不熟悉 导致某些查询可能不知道如何实现 于是采用了原生sql 今天 就让我们来总结一下常用的o
  • Windows10 配置 Swin-Transformer 踩坑记

    机器配置 rtx 3090 CUDA 11 1 Python 3 8 pytorch 1 9 0 步骤 1 下载Swin Transformer git clone recursive https github com SwinTransf
  • centos7执行命令iptables 出现Unit iptables.service failed to load: No such file or directory.

    解决方式 安装iptables services yum install iptables services 开机启动 systemctl enable iptables systemctl stop iptables systemctl
  • 更新powershell 7.3.2

    最近在使用VsCode时打开中断会时常提示你powershell已经更新前往地址下载 但是跳转到的页面描述有时候看不太清晰 于是去b站结合网络文档还是成功更新了 有兴趣的朋友可以通过这个链接查看一下在线文档 gt powershell的在线
  • ASPxTextBox中数据有效性设置

    1 选中ASPxTextBox控件 2 设置属性 Validationsettings中errordisplaymode requiredfield中errortext和isrequired 3 结果 4 总图
  • 100天精通Python(可视化篇)——第78天:matplotlib绘图模块基础入门大全

    文章目录 专栏导读 一 课程介绍 为什么要学习matplotlib 什么是matplotlib 二 绘制折线图 基础绘图 设置图片大小和分辨率 调整X或者Y轴上的刻度 设置中文显示 坐标轴添加描述信息 绘制网格 双折线图 添加图例 自定义绘
  • unittest使用ddt数据驱动的小demo

    一 ddt简介 1 ddt是 data driven testing的缩写 中文含义是数据驱动测试 2 ddt通常与unittest组合使用 常用的包有ddt data unpack file data 我这边使用前两种 二 ddt安装 1
  • word怎么改一张纸的方向_word单页怎么改变纸张方向

    word改变单页纸张方向的方法 1 将插入点移动到需要修改的单页的开头 2 在 布局 菜单中 分隔符 下选择 下一页 3 点击 纸张方向 选择 横向 4 将插入点移动到下一页的开头 再点击 分隔符 的 下一页 再点击 纵向 即可 本教程操作
  • el-tree和el-table相关使用

    文章目录 el tree实现模糊查询 el tree实现node节点增删改 el tree 实现节点懒加载 el tree获取所有选中的当前节点 el tree获取当前节点及其选中父节点 el table 获取多选行的所有节点 el tab