el-tree多选和联动

 根据角色不同类别改变树的选择和禁用,下面我将所有代码复制过来,如果有变量确实自行补充

html 

<template>
  <div class="manageRole">
    <div class="manageRole-header">
      <el-input
        v-model="searchValue"
        @change="getRoleList()"
        clearable
        placeholder="搜索"
        size="mini"
        suffix-icon="el-icon-search"
      ></el-input>
      <span>角色:</span>
      <el-select v-model="jsValue" clearable size="mini" placeholder="请选择">
        <el-option
          v-for="(item, index) in roleList"
          :key="index"
          :label="item.name"
          :value="item.name"
        >
        </el-option>
      </el-select>
      <span>权限:</span>
      <el-select v-model="qxValue" clearable size="mini" placeholder="请选择">
        <el-option
          v-for="(item, index) in functionList"
          :key="index"
          :label="item.name"
          :value="item.name"
        >
        </el-option>
      </el-select>
      <el-button @click="getChange()" size="mini" class="button-self-style" style="float: right"
        >新增</el-button
      >
    </div>
    <el-table :data="roleList" style="width: 100%" stripe>
      <el-table-column type="index" label="序号" width="100" align="center" show-overflow-tooltip>
      </el-table-column>
      <el-table-column
        prop="name"
        label="角色名称"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="角色类别" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{
            scope.row.type == 1 ? '应急局' : scope.row.type == 2 ? '行业部门' : '乡镇街道'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="permodel"
        label="权限模块"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="description" label="角色说明" align="center" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" align="center" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="created_user" label="创建者" align="center" show-overflow-tooltip>
      </el-table-column>
      <el-table-column label="操作" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <a style="cursor: pointer; color: #2dfdfc" @click="getChange(scope.row)">
            <i class="el-icon-edit"></i>编辑</a
          >
          <a style="cursor: pointer; margin-left: 20px" @click="deleteUser(scope.row)">
            <i class="el-icon-delete"></i>删除</a
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChange"
      @current-change="currentChange"
      :page-size="page.pageSize"
      :total="page.total"
      :current-page="1"
      :page-sizes="[24, 48, 72, 96]"
      style="float: right; margin-top: 10px"
      background
      layout=" prev, pager, next,sizes,jumper"
    >
    </el-pagination>

    <el-dialog
      class="allDialogStyle"
      :visible.sync="dialogChange"
      center
      width="430px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <span class="dialog-footer" style="position: absolute; right: 10px"> </span>
      <el-tabs v-model="activeName">
        <el-tab-pane :label="ifCreate ? '新增用户信息' : '修改用户信息'" name="first">
          <!-- <p></p> -->
          <div style="width: 100%; margin-top: 10px">
            <span style="color: red">*</span>
            <span style="color: #fff">角色名称:</span>
            <el-input v-model="tempData.name" clearable size="mini"></el-input>
          </div>
          <div style="width: 100%">
            <span style="color: red">*</span>
            <span style="color: #fff">角色类别:</span>
            <el-radio-group v-model="jsRadio" @change="jsChange">
              <el-radio label="1">应急局</el-radio>
              <el-radio label="2">行业部门</el-radio>
              <el-radio label="3">乡镇街道</el-radio>
            </el-radio-group>
          </div>
          <div style="width: 100%">
            <span style="color: red">*</span>
            <span style="color: #fff">权限模块:</span>
            <div
              style="
                border: 1px solid rgba(15, 189, 205, 0.42);
                padding: 5px;
                width: 100%;
                margin: 10px 0;
                display: flex;
                justify-content: space-between;
              "
            >
              <el-tree
                :data="treeData"
                show-checkbox
                node-key="id"
                :props="{
                  children: 'children',
                  label: 'name'
                }"
                ref="Tree"
                check-on-click-node
                :check-strictly="true"
                :expand-on-click-node="false"
                @check-change="handleCheckChange"
                @node-click="nodeClick"
                style="max-height: 500px; overflow-y: auto; width: 100%"
              >
                <span
                  slot-scope="{ data }"
                  :style="{
                    color: !data.disabled ? '#fff' : '#6e7f95'
                  }"
                >
                  {{ data.name }}
                </span>
              </el-tree>
            </div>
          </div>
          <div style="width: 100%">
            <span style="color: #fff">角色说明:</span>
            <el-input
              type="textarea"
              v-model="tempData.description"
              clearable
              size="mini"
            ></el-input>
          </div>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" class="button-self-style" @click="handleClose">取 消</el-button>
        <el-button
          size="mini"
          class="button-self-style"
          type="primary"
          @click="changeUser(false), handleClose"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      activeName: 'first',
      page: {
        total: 0,
        pageNum: 0,
        pageSize: 24
      }, // 分页
      jsValue: '',
      searchValue: '',
      qxValue: '',
      roleList: [],
      tempData: {},
      dialogChange: false,
      ifCreate: false,
      treeData: [],
      functionList: [],
      defaultCheck: [],
      permids: [], // 编辑选中的id
      jsRadio: '1' // 默认角色
    }
  },
  props: {},
  components: {},
  computed: {
    ...mapGetters({
      userInfo: 'getUserInfo'
    }),
    onChange(val) {
      const { jsValue, qxValue } = this // 同时监听多个属性
      return { jsValue, qxValue }
    }
  },
  watch: {
    onChange(val) {
      this.getRoleList()
    }
  },
  mounted() {
    this.getRoleList()
    this.getFunctionList()
  },
  methods: {
    // 获取登录和编辑用户权限
    getRoleList() {
      let json = []
      this.roleList = []
      if (this.searchValue) {
        this.page.pageNum = 0 // 筛选后从第一页开始
        json.push({ field: 'name', operator: 'EQ', value: this.searchValue })
      }
      if (this.qxValue) {
        this.page.pageNum = 0 // 筛选后从第一页开始
        json.push({ field: 'permodel', operator: 'FQ', value: this.qxValue })
      }
      if (this.jsValue) {
        this.page.pageNum = 0 // 筛选后从第一页开始
        json.push({ field: 'name', operator: 'EQ', value: this.jsValue })
      }
      let params = {
        pageNo: this.page.pageNum,
        pageSize: this.page.pageSize,
        simcode: this.userInfo.simcode,
        keyword: JSON.stringify(json)
      }
      this.$store.dispatch('getRoleList', params).then((res) => {
        if (res.data.code === 1) {
          this.roleList = res.data.data
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    getChange(val) {
      this.dialogChange = true
      this.defaultCheck = []
      this.permids = []
      this.tempData = {
        code: (val && val.code) || this.userInfo.simcode,
        created_at: (val && val.created_at) || this.formatTime(),
        created_user: (val && val.created_user) || this.userInfo.xzq_name,
        description: (val && val.description) || '', // 角色描述
        gjjsfyx: (val && val.gjjsfyx) || 0,
        issystem: (val && val.issystem) || '0', // 是否预置
        name: (val && val.name) || '',
        permodel: (val && val.permodel && val.permodel.split(',')) || [], // 模块
        shengsfyx: (val && val.shengsfyx) || 0,
        shisfyx: (val && val.shisfyx) || 1,
        xsfyx: (val && val.xsfyx) || 1,
        id: (val && val.id) || '',
        type: (val && val.type) || this.jsRadio // 默认角色
      }
      // debugger
      this.$nextTick(() => {
        if (val) {
          this.ifCreate = false // 编辑用户
          this.jsRadio = this.tempData.type + ''
          if (this.tempData.permodel && this.tempData.permodel.length > 0) {
            for (let index = 0; index < this.tempData.permodel.length; index++) {
              let item = this.tempData.permodel[index]
              this.treeData = this.getDgData(this.functionList, item, this.jsRadio, 1)
            }
          } else {
            this.treeData = this.getDgData(this.functionList, null, this.jsRadio, 1)
          }
        } else {
          this.ifCreate = true // 新建
          this.treeData = this.getDgData(this.functionList, null, this.jsRadio, 1)
        }
        console.log(this.treeData)
        this.$refs.Tree.setCheckedKeys(this.defaultCheck) // 获取已经设置的资源后渲染
      })
    }, // 获取选中数据
    getDgData(data, item, js, ifChildrenDis = 1) {
      let pushData = (value) => {
        if (this.ifCreate) {
          this.tempData.permodel.push(value.name)
          this.defaultCheck.push(value.id) //
          this.permids.push({ id: value.id, pid: value.pid })
        } else if (value.name == item) {
          // debugger
          this.defaultCheck.push(value.id) // 编辑默认选中
          this.permids.push({ id: value.id, pid: value.pid })
        }
      }
      for (let index = 0; index < data.length; index++) {
        data[index].disabled = false
        const ele = data[index]
        // 创建根据默认的角色选中对应权限 ..
        // [管理员(权限全部默认打钩)\行业部门(驾驶舱,平台资源,数据管理)\乡镇街道(驾驶舱\平台资源),没有打钩的权限置灰],选择逐级递增,
        // ifChildrenDis   :1全选  2 禁用  3 不管
        // debugger
        if (js == '1') {
          pushData(ele)
        } else if (js == '2') {
          if (ele.pid == '0') {
            // 遍历最外层
            if (['1', '2', '5'].includes(ele.id)) {
              pushData(ele)
              ifChildrenDis = 1
            }
            // else if (ele.id == '5') {
            //   ifChildrenDis = 3 // 行业部门的数据管理不管,让用户自己选
            // }
            else {
              ifChildrenDis = 2
              ele.disabled = true // 除了默认选中的都禁用
            }
          } else {
            // 子级 的判断根据父级传参
            if (ifChildrenDis == 1) {
              pushData(ele) // 子级选择
            } else if (ifChildrenDis == 2) {
              ele.disabled = true // 子级禁用
            } // 3子级不管
          }
        } else if (js == '3') {
          if (ele.pid == '0') {
            // 遍历最外层
            if (['1', '2'].includes(ele.id)) {
              pushData(ele)
            } else {
              ifChildrenDis = 2
              ele.disabled = true // 除了默认选中的都禁用
            }
          } else {
            // 子级 的判断根据父级传参
            if (ifChildrenDis == 1) {
              pushData(ele) // 子级选择
            } else if (ifChildrenDis == 2) {
              ele.disabled = true // 子级禁用
            } // 3子级不管
          }
        }

        if (ele.children) {
          this.getDgData(ele.children, item, js, ifChildrenDis)
        }
      }
      return data
    }, // 递归获取
    jsChange(val) {
      // debugger
      this.$nextTick(() => {
        this.tempData.type = val
        this.defaultCheck = []
        this.permids = []
        this.treeData = []
        if (this.ifCreate) {
          this.tempData.permodel = []
        }
        this.ifCreate = true // 切换类别改为创建模式
        this.treeData = JSON.parse(JSON.stringify(this.getDgData(this.functionList, null, val, 1))) // 重新更新整个视图
        this.$refs.Tree.setCheckedKeys(this.defaultCheck) // 获取已经设置的资源后渲染
        // console.log(this.defaultCheck)
      })
    }, // 编辑新建默认角色
    changeUser() {
      if (this.tempData.name == '' || this.tempData.permodel.length == 0) {
        this.$message.error('请填写完全必选项!')
        return
      }
      console.log(this.tempData)
      // debugger
      this.$store
        .dispatch('addOrUpdateRole', { role: this.tempData, permids: this.permids })
        .then((res) => {
          if (res.data.code === 1) {
            this.$message.success(res.data.msg)
            this.getRoleList()
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch((err) => {
          this.$message.error(err.data.msg)
        })
      this.dialogChange = false
    }, // 编辑用户信息
    deleteUser(val) {
      if (val.issystem == 1) {
        this.$message.error('系统预置角色不能删除')
        return
      }
      this.$confirm('是否删除该用户', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        showClose: false,
        customClass: 'self-confirm-box allDialogStyle',
        cancelButtonClass: 'button-self-style el-button--mini',
        confirmButtonClass: 'button-self-style el-button--mini'
      })
        .then(() => {
          this.$store.dispatch('DeleteRole', { role_id: val.id }).then((res) => {
            if (res.data.code === 1) {
              this.getRoleList()
            } else if (res.data.msg == '当前角色存在用户绑定关系,是否仍要删除?') {
              this.$confirm(res.data.msg, '确认删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                showClose: false,
                customClass: 'self-confirm-box allDialogStyle',
                cancelButtonClass: 'button-self-style el-button--mini',
                confirmButtonClass: 'button-self-style el-button--mini'
              })
                .then(() => {
                  this.$store.dispatch('DeleteRole', { role_id: val.id, sfrysc: 1 }).then((res) => {
                    if (res.data.code === 1) {
                      this.getRoleList()
                    } else {
                      this.$message.error(res.data.msg)
                    }
                  })
                })
                .catch(() => {
                  this.$message.info('已取消')
                })
            } else {
              this.$message.error(res.data.msg)
            }
          })
        })
        .catch(() => {
          this.$message.info('已取消')
        })
    }, // 删除用户
    getFunctionList() {
      this.functionList = []
      this.$store.dispatch('getFunctionList', {}).then((res) => {
        if (res.data.code == 1) {
          this.functionList = res.data.data.filter((ele) => {
            return { id: ele.id, name: ele.name }
          })
        }
      })
    }, // 权限书
    handleCheckChange(data, checked, indeterminate) {
      let arr = this.$refs.Tree.getCheckedNodes()
      this.tempData.permodel = []
      this.permids = []
      this.defaultCheck = []
      arr.forEach((item) => {
        this.defaultCheck.push(item.id) // 编辑默认选中
        this.tempData.permodel.push(item.name)
        this.permids.push({ id: item.id, pid: item.pid })
      })
      // console.log(arr, 'chenck')
      // console.log(this.permids)
      // console.log(this.tempData.permodel)
      // console.log(this.defaultCheck)
    }, // 多选
    handleClose() {
      this.dialogChange = false
      this.jsRadio = '1'
      this.tempData = {}
      this.permids = []
      this.defaultCheck = []
    }, // 关闭弹窗
    // 分页数据
    currentChange(val) {
      this.page.pageNum = val - 1
      this.getRoleList()
    },
    sizeChange(val) {
      this.page.pageSize = val
      this.getRoleList()
    },
    nodeClick(data, node) {
      // 这个方法是勾选父级子级也默认勾选 取消子级不影响父级
      // debugger
      this.childNodesChange(node)
      // 这个方法是勾选子级默认把父级也勾选上
      this.parentNodesChange(node)
      // this.$refs.Tree.getCheckedNodes() 这个方法是官网自带的 若节点可被选择(即    show-checkbox 为 true),则返回目前被选中的节点所组成的数组
      let arr = this.$refs.Tree.getCheckedNodes()
      // debugger
      this.tempData.permodel = []
      this.permids = []
      this.defaultCheck = []
      arr.forEach((item) => {
        this.defaultCheck.push(item.id) // 编辑默认选中
        this.tempData.permodel.push(item.name)
        this.permids.push({ id: item.id, pid: item.pid })
      })
      console.log(arr, 'node')
      // this.$message.info(`当前已选择--${this.tempData.permodel}`)
      // console.log(this.defaultCheck, 'defaultCheck')
    },
    childNodesChange(node) {
      let len = node.childNodes.length
      if (len > 0) {
        for (let i = 0; i < len; i++) {
          if (!node.checked) {
            node.childNodes[i].checked = false
          } else {
            node.childNodes[i].checked = true
          }
          this.childNodesChange(node.childNodes[i])
        }
      }
    },
    parentNodesChange(node) {
      if (node.parent) {
        for (let key in node) {
          if (key == 'parent') {
            node[key].checked = true
            this.parentNodesChange(node[key])
          }
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.manageRole {
  width: 100%;
  height: 100%;
  overflow: hidden;
  .manageRole-header {
    width: 100%;
    padding: 10px 0;
    color: #fff;
    font-size: 14px;
    /deep/ .el-input {
      width: 200px;
    }
    > span {
      margin-left: 20px;
    }
  }
  /deep/ .el-table {
    border-radius: 5px;
    border: none;
    .el-table__body-wrapper {
      overflow-y: auto;
      overflow-x: hidden;
      height: calc(100vh - 280px);
    }
  }
  .allDialogStyle {
    overflow: hidden;
    /deep/ .el-tree {
      color: #fff;
      background: none;
      .el-tree-node.is-current > .el-tree-node__content {
        background: rgba(221, 221, 221, 0.4);
      }
      .el-tree-node .el-tree-node__content .is-leaf {
        background: none !important;
      }
      .el-tree-node .el-tree-node__content:hover {
        background: rgba(221, 221, 221, 0.4);
      }
    }
  }
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值