vue部门层级展示,可以选择多个部门

<template>
  <div class="s">
    <!-- 操作按钮 -->
    <div class="shang">
      <el-input v-model="searchText" placeholder="请输入搜索关键词" style="width: 500px;"></el-input>
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button @click="resetForm">重置</el-button>
    </div>
    <br>
    <el-button type="primary" @click="showAddDialog">新增用户</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="user_email" label="邮箱号"></el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          {{ getRoleName(scope.row.role_id) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="部门">
          <template slot-scope="scope">
            <span v-for="(department, index) in scope.row.department_id" :key="department">
              {{ department }}
            </span>
          </template>
        </el-table-column> -->
      <el-table-column label="部门">
        <template slot-scope="scope">
          <span v-for="(department, index) in scope.row.department_id" :key="department">
            {{ department.split(' ----- ').pop() }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.user_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="isDialogVisible">
      <el-form :model="form">
        <el-form-item label="姓名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="邮箱号">
          <el-input v-model="form.user_email"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <br>
          <el-select v-model="form.role" style="width:200px">
            <el-option v-for="role in roles" :key="role.id" :label="role.role_name" :value="role.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- :options="deptOptions"指定选项数据源。
              :show-count="true"显示选中项的数量。
            :normalizer="normalizer"指定一个函数来格式化选项的显示。
            : placeholdermultiple允许选择多个部门。     
        -->
        <el-form-item label="归属部门">
          <treeselect v-model="form.department_ids" :options="deptOptions" :show-count="true" placeholder="请选择归属部门"
            :normalizer="normalizer" multiple />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: { Treeselect },
  data() {
    return {
      searchText: '',
      deptOptions: [],
      tableData: [],
      roles: [],
      isDialogVisible: false,
      dialogTitle: '新增用户',
      form: {
        id: '',
        name: '',
        user_email: '',
        role: '',
        department_ids: []
      },
      setRoleDialogVisible: false,
      setDepDialogVisible: false,
      userInfo: []
    };
  },
  mounted() {
    this.handleSearch();
    this.setRole();
    this.setDep();
  },
  computed: {
    //   deptOptionsWithCurrentUserDept() {
    //     // 克隆deptOptions数组以避免直接更改原始数据
    //     let options = JSON.parse(JSON.stringify(this.deptOptions));

    //     // 寻找当前用户的部门对象
    //     let currentUserDept = options.find(dept => dept.id === this.currentUserDepartmentId);

    //     // 如果找到当前用户的部门对象,则添加到显示列表的最前面
    //     if (currentUserDept) {
    //       options.unshift(currentUserDept);
    //     }
    //   //  Array.prototype.unshift  方法将该部门对象添加到 options 数组的最前面。
    //   // unshift 方法会将元素插入到数组的开头,并返回新的数组长度。
    //     //返回处理后的 options 数组
    //     return options;
    //   }
    // 
  },
  methods: {
    getRoleName(roleId) {
      const role = this.roles.find(role => role.id === roleId);
      return role ? role.role_name : '';
    },
    resetForm() {
      this.searchText = '';
      this.handleSearch();
    },
    async search() {
      try {
        const usersResponse = await axios.get('http://127.0.0.1:8000/users/', {
          params: {
            query: this.searchText
          }
        });
        this.tableData = usersResponse.data;

        // 同时获取部门信息
        const deptResponse = await axios.get('http://127.0.0.1:8000/departments/');
        this.deptOptions = deptResponse.data;
        console.log("this.deptOptions部门", this.deptOptions);
      } catch (error) {
        console.error('搜索时出错:', error);
      }
    },
    async handleSearch() {
      try {
        const usersResponse = await axios.get('http://127.0.0.1:8000/users/get_user_details_extended/');
        this.tableData = usersResponse.data;
        // 同时获取部门信息
        const deptResponse = await axios.get('http://127.0.0.1:8000/departments/');
        this.deptOptions = deptResponse.data;
        console.log("this.deptOptions部门1", this.deptOptions);
      } catch (error) {
        console.error('Error fetching users:', error);
      }
    },
    async setRole() {
      try {
        const response = await axios.get('http://127.0.0.1:8000/roles/');
        this.roles = response.data;
        this.setRoleDialogVisible = true;
      } catch (error) {
        console.error('Error fetching roles:', error);
      }
    },
    normalizer(node) {
      if (node.children) {
        return {
          id: node.id,
          label: node.name.split(' - ').pop(), // 只获取子部门名称
          children: node.children
        };
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // async setDep() {
    //   try {
    //     const response = await axios.get('http://127.0.0.1:8000/departments/');
    //     this.deptOptions = response.data;
    //     this.setDepDialogVisible = false;
    //     console.log("this.deptOptions部门", this.deptOptions);
    //   } catch (error) {
    //     console.error('Error fetching departments:', error);
    //   }
    // },
    showAddDialog() {
      this.dialogTitle = '新增用户11111';
      this.form = {
        id: '',
        name: '',
        user_email: '',
        role_id: '',
        department_ids: []
      };
      this.isDialogVisible = true;
    },
    async setDep() {
  try {
    const response = await axios.get('http://127.0.0.1:8000/departments/');
    this.deptOptions = response.data.map(department => ({
      id: department.id, // 假设返回的数据中有 id 字段表示部门 ID
      name: department.name
    }));
    this.setDepDialogVisible = false;
    console.log("this.deptOptions部门", this.deptOptions);
  } catch (error) {
    console.error('Error fetching departments:', error);
  }
},
showEditDialog(row) {
  this.dialogTitle = '编辑用户1111';
  this.form = {
    id: row.user_id,
    name: row.name,
    user_email: row.user_email,
    role: row.role_id
  };

  // 根据部门名称找到对应的 ID
  if (row.department_id && Array.isArray(row.department_id)) {
    this.form.department_ids = row.department_id.map(departmentName => {
      const department = this.deptOptions.find(dept => dept.name === departmentName);
      return department? department.id : null;
    });
  } else {
    this.form.department_ids = [];
  }

  this.isDialogVisible = true;
  console.log("this.form编辑用户=================", this.form);
},

  //   showEditDialog(row) {
  
  // this.dialogTitle = '编辑用户1111';
  // this.form = {
  //   id: row.user_id,
  //   name: row.name,
  //   user_email: row.user_email,
  //   role: row.role_id
  // };
  //   console.log('row.department_id:', row.department_id.value);
  // if (Array.isArray(row.department_id)) {
  //   this.form.department_ids = row.department_id;
  // } else {
  //   this.form.department_ids = [row.department_id];
  //   this.form.department_ids = [];
  // }



  // this.isDialogVisible = true;
  // console.log("this.form编辑用户=================", this.form);
  // },

    async handleSubmit() {
      const payload = {
        id: this.form.id,
        name: this.form.name,
        user_email: this.form.user_email,
        role_id: this.form.role,
        department_ids: this.form.department_ids    // 将数字数组形式的部门 ID 转换为字符串
      };
      console.log("用户编辑部分111111111111111111111111", this.form.id);
      if (this.form.id !== "") {
        try {
          await axios.put(`http://127.0.0.1:8000/search/update_user/${this.form.id}`, payload);
          this.$message.success('用户编辑成功');
          this.handleSearch();
        } catch (error) {
          console.error('Error updating user:', error);
        }
      } else {
        try {
          await axios.post('http://127.0.0.1:8000/search/create_user/', payload);
          this.$message.success('新增用户成功');
          this.handleSearch();
        } catch (error) {
          console.error('Error adding user:', error);
        }
      }
      this.isDialogVisible = false;
    },

    async handleDelete(id) {
      try {
        await axios.delete(`http://127.0.0.1:8000/users/${id}/`);
        this.$message.success('用户删除成功');
        this.handleSearch();
      } catch (error) {
        console.error('Error deleting user:', error);
      }
    }
  }
};
</script>

<style>
/* 样式可以按需添加 */
.s {
  margin-left: 20px;
  margin-top: 20px;
}

.shang {
  margin-top: 20px;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值