feat: 添加部门查询

添加部门查询
This commit is contained in:
zc
2021-12-07 00:07:18 +08:00
parent 7d180983fb
commit a021f3e5e5
5 changed files with 899 additions and 1 deletions

View File

@@ -4,5 +4,5 @@
NODE_ENV='development'
VITE_APP_TITLE = '管理系统'
VITE_APP_PORT = 9527
VITE_APP_PORT = 9528
VITE_APP_BASE_API = '/dev-api'

68
src/api/system/dept.ts Normal file
View File

@@ -0,0 +1,68 @@
import request from '@/utils/request'
// export function list(queryParams:object) {
// return request({
// url: '/youlai-admin/api/v1/oauth-clients',
// method: 'get',
// params: queryParams
// })
// }
export const listDept = (queryParams?: object) => {
return request({
url: '/youlai-admin/api/v1/depts/table',
method: 'get',
params: queryParams
})
}
export const getDept = (deptId: any) => {
return request({
url: '/youlai-admin/api/v1/depts/select',
method: 'get'
})
}
// export const listDeptExcludeChild = (deptId: any) => {
// return https().request<RootObject<any>>(`system/dept/list/exclude/${deptId}`, Method.GET, undefined, ContentType.form)
// }
export const delDept = (deptId: any) => {
return request({
url: '/youlai-admin/api/v1/depts/'+deptId,
method: 'delete',
})
}
// 新增部门
export const addDept = (data: any) => {
return request({
url: '/youlai-admin/api/v1/depts',
method: 'post',
data: data
})
}
// 修改部门
export const updateDept = (data: any) => {
return request({
url: '/youlai-admin/api/v1/depts/' + id,
method: 'put',
data: data
})
}
// // 根据角色ID查询部门树结构
// export const roleDeptTreeselect = (roleId: number | string) => {
// return https().request<any>(`system/dept/roleDeptTreeselect/${roleId}`, Method.GET, undefined, ContentType.form)
// }
//
// // 查询部门下拉树结构
//
// export const treeselect = () => {
// return https().request<RootObject<any>>('system/dept/treeselect', Method.GET, undefined, ContentType.form)
// }

View File

@@ -0,0 +1,200 @@
<template>
<el-select
v-model="valueTitle"
:clearable="clearable"
@clear="clearHandle"
:placeholder="placeholder"
>
<el-option
:value="valueTitle"
:label="valueTitle"
class="options"
>
<el-tree
id="tree-option"
ref="selectTree"
:accordion="accordion"
:data="options"
:props="treeProps"
:node-key="treeProps.value"
:default-expanded-keys="defaultExpandedKey"
@node-click="handleNodeClick"
:disabled="disabled"
/>
</el-option>
</el-select>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, nextTick, onMounted, getCurrentInstance, PropType, watch } from 'vue'
interface TreeProps {
value: number
label: string
children: string
}
export default defineComponent({
name: 'ElTreeSelect',
props: {
placeholder: {
type: String,
default: ''
},
user: {
type: Boolean,
default: false
},
// 选项列表数据(一维数组)
originOptions: { type: Array, required: true },
// 选项列表数据(树形结构的对象数组)
options: { type: Array, required: true },
// 初始值
defalut: { type: Number, default: null },
// 可清空选项
clearable: { type: Boolean, default: true },
// 自动收起
accordion: { type: Boolean, default: false },
treeProps: {
type: Object as PropType<TreeProps>,
default: () => {
return {
value: 'menuId',
label: 'menuName',
children: 'children'
}
}
},
disabled: {
type: Boolean, default: false
}
},
emits: ['callBack'],
setup(props, ctx) {
console.log(props.options)
console.log(props.treeProps)
const instance = getCurrentInstance() as any
const state = reactive({
valueId: 0,
valueTitle: '',
defaultExpandedKey: Array<number>()
})
// 初始化滚动条
const initScroll = () => {
nextTick(() => {
const scrollWrap = document.querySelectorAll('.el-scrollbar .el-select-dropdown__wrap')[0] as any
const scrollBar = document.querySelectorAll('.el-scrollbar .el-scrollbar__bar') as any
scrollWrap.style.cssText = 'margin: 0px; max-height: none; overflow: hidden;'
scrollBar.forEach((ele: any) => {
ele.style.width = 0
})
})
}
// 清空选中样式
const clearSelected = () => {
const allNode = document.querySelectorAll('#tree-option .el-tree-node')
allNode.forEach((element) => element.classList.remove('is-current'))
}
const initHandle = () => {
initScroll()
}
// 处理默认值并显示
const defaultValue = () => {
console.log('xxxxxx')
if (props.defalut !== null) {
const deafaultModels = props.originOptions.filter((item: any) => {
return item[props.treeProps.value] === props.defalut
})
if (deafaultModels.length > 0) {
state.valueId = props.defalut
state.valueTitle = (deafaultModels[0] as any)[props.treeProps.label]
} else {
if (!props.user) {
state.valueId = 0
state.valueTitle = '主类目'
} else {
state.valueId = 0
state.valueTitle = ''
}
}
instance.ctx.$refs.selectTree.setCurrentKey(props.defalut)
state.defaultExpandedKey = [props.defalut] as number[]
}
}
onMounted(() => {
initHandle()
})
watch(() => props.options, () => {
if (props.options) {
defaultValue()
}
})
// 更新数据
const updateData = (value: any, label: any) => {
state.valueTitle = label
state.valueId = value
state.defaultExpandedKey = []
ctx.emit('callBack', value)
}
// 点击节点调用
const handleNodeClick = (node: any) => {
updateData(node[props.treeProps.value], node[props.treeProps.label])
}
// 清除选中
const clearHandle = () => {
updateData(null, null)
clearSelected()
}
return {
...toRefs(state),
handleNodeClick,
clearHandle
}
}
})
</script>
<style scoped>
.el-select.el-select--medium{
width: 100%;
}
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
height: auto;
max-height: 274px;
padding: 0;
overflow: hidden;
overflow-y: auto;
}
.el-select-dropdown__item.selected {
font-weight: normal;
}
ul li :deep(.el-tree .el-tree-node__content) {
height: auto;
padding: 0 20px;
}
.el-tree-node__label {
font-weight: normal;
}
.el-tree :deep(.is-current .el-tree-node__label) {
color: #409eff;
font-weight: 700;
}
.el-tree :deep(.is-current .el-tree-node__children .el-tree-node__label) {
color: #606266;
font-weight: normal;
}
</style>

124
src/utils/ruoyi.ts Normal file
View File

@@ -0,0 +1,124 @@
/*
* @Description:
* @Autor: scy😊
* @Date: 2021-02-04 09:08:51
* @LastEditors: ZY
* @LastEditTime: 2021-02-23 14:44:09
*/
// const baseURL = process.env.VUE_APP_BASE_API
//
// export function download(fileName: any) {
// window.location.href = baseURL + '/common/download?fileName=' + encodeURI(fileName) + '&delete=' + true
// }
// 添加日期范围
type Params = {[key: string]: any}
export const addDateRange = (params: Params, dateRange: any, propName?: any) => {
const search = params
search.params = {}
if (dateRange !== null && dateRange !== '') {
if (typeof (propName) === 'undefined') {
search.params.beginTime = dateRange[0]
search.params.endTime = dateRange[1]
} else {
search.params['begin' + propName] = dateRange[0]
search.params['end' + propName] = dateRange[1]
}
}
console.log(search)
return search
}
/**
* 构造树型结构数据
* @param {*} data 数据源
* @param {*} id id字段 默认 'id'
* @param {*} parentId 父节点字段 默认 'parentId'
* @param {*} children 孩子节点字段 默认 'children'
* @param {*} rootId 根Id 默认 0
*/
export const handleTree = (data?: any, id?: any, parentId?: any, children?: any, rootId?: any) => {
id = id || 'id'
parentId = parentId || 'parentId'
children = children || 'children'
const parentIds = data.map((item: any) => { return item[parentId] })
rootId = rootId || Math.min(...parentIds) || 0
// 对源数据深度克隆
const cloneData = JSON.parse(JSON.stringify(data))
// 循环所有项
const treeData = cloneData.filter((father: any) => {
const branchArr = cloneData.filter((child: any) => {
// 返回每一项的子级数组
return father[id] === child[parentId]
})
if (branchArr.length > 0) {
father.children = branchArr
}
// 返回第一层
return father[parentId] === rootId
})
return treeData !== '' ? treeData : data
}
// 回显数据字典
export const selectDictLabel = (datas: Array<any>, value: string) => {
const actions: string[] = []
Object.keys(datas).some((key) => {
if (datas[key].dictValue === value) {
actions.push(datas[key].dictLabel)
return true
}
})
return actions.join('')
}
// 转换字符串undefined,null等转化为""
export function praseStrEmpty(str: null | undefined) {
if (!str || str === undefined || str === null) {
return ''
}
return str
}
// 日期格式化
export function parseTime(time: any, pattern: any) {
if (arguments.length === 0 || !time) {
return null
}
const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
} else if (typeof time === 'string') {
time = time.replace(new RegExp(/-/gm), '/')
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const timestr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result: any, key: any) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return timestr
}

View File

@@ -0,0 +1,506 @@
<template>
<div class="app-container">
<el-form
:model="queryParams"
ref="queryForm"
:inline="true"
v-show="showSearch"
>
<el-form-item
label="部门名称"
prop="name"
>
<el-input
v-model="queryParams.name"
placeholder="请输入部门名称"
size="small"
@keyup.enter="handleQuery"
/>
</el-form-item>
<el-form-item
label="状态"
prop="status"
>
<el-select
v-model="queryParams.status"
placeholder="部门状态"
clearable
size="small"
>
<el-option
v-for="dict in statusOptions"
:key="dict.dictValue"
:label="dict.dictLabel"
:value="dict.dictValue"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button
class="filter-item"
type="primary"
size="mini"
:icon="Search"
@click="handleQuery"
>
搜索
</el-button>
<el-button
:icon="Refresh"
size="mini"
@click="resetQuery"
>
重置
</el-button>
</el-form-item>
</el-form>
<el-row
:gutter="10"
class="mb8"
>
<el-col :span="1.5">
<el-button
type="primary"
plain
:icon="Plus"
size="mini"
@click="handleAdd"
>
新增
</el-button>
</el-col>
<!-- <right-toolbar
v-model:showSearch="showSearch"
@queryTable="getList"
/> -->
</el-row>
<el-table
v-loading="loading"
:data="deptList"
row-key="deptId"
default-expand-all
:tree-props="{children: 'children', hasChildren: 'hasChildren'}"
>
<el-table-column prop="name" label="部门名称"/>
<el-table-column prop="status" label="状态" width="100">
<template #default="scope">
<el-tag v-if="scope.row.status==1" type="success">正常</el-tag>
<el-tag v-else type="info">禁用</el-tag>
</template>
</el-table-column>
<el-table-column prop="sort" label="显示排序" width="200"/>
<el-table-column
label="操作"
align="center" width="150"
>
<template #default="scope">
<el-button
type="primary"
:icon="Edit"
size="mini"
circle
plain
@click.stop="handleUpdate(scope.row)"
>
</el-button>
<el-button
type="success"
size="mini"
:icon="Plus"
circle
plain
@click.stop="handleAdd(scope.row)"
>
</el-button>
<el-button
type="danger"
:icon="Delete"
size="mini"
circle
plain
@click.stop="handleDelete(scope.row)">
</el-button>
</template>
</el-table-column>
</el-table>
<!-- 添加或修改部门对话框 -->
<el-dialog
:title="title"
v-model="open"
width="600px"
@opened="dialogshow"
>
<el-form
ref="formDialog"
:model="formVal"
label-width="80px"
>
<el-row>
<el-col
:span="24"
v-if="parentId !== 0"
>
<el-form-item
label="上级部门"
prop="parentId"
>
<Treeselect
:treeProps="props"
:options="deptOptions"
placeholder="请选择归属部门"
:originOptions="originOptions"
:defalut="formVal.parentId"
:user="true"
@callBack="getDeptId"
:disabled="disabled"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item
label="部门名称"
prop="deptName"
>
<el-input
v-model="formVal.deptName"
placeholder="请输入部门名称"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item
label="显示排序"
prop="orderNum"
>
<el-input-number
:min="0"
v-model="formVal.orderNum"
controls-position="right"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item
label="负责人"
prop="leader"
>
<el-input
v-model="formVal.leader"
placeholder="请输入负责人"
maxlength="20"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item
label="联系电话"
prop="phone"
>
<el-input
v-model="formVal.phone"
placeholder="请输入联系电话"
maxlength="11"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item
label="邮箱"
prop="email"
>
<el-input
v-model="formVal.email"
placeholder="请输入邮箱"
maxlength="50"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="部门状态">
<el-radio-group v-model="formVal.status">
<el-radio
v-for="dict in statusOptions"
:key="dict.dictValue"
:label="dict.dictValue"
>
{{ dict.dictLabel }}
</el-radio>
</el-radio-group>
</el-form-item>
</el-col>
</el-row>
</el-form>
<template #footer>
<div
class="dialog-footer"
>
<el-button
type="primary"
@click="submitForm"
>
</el-button>
<el-button @click="cancel">
</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, unref, ref } from 'vue'
import {Search, Plus, Edit, Refresh, Delete} from '@element-plus/icons'
import { listDept, getDept, delDept, updateDept, addDept } from '@/api/system/dept'
import treeselect from '@/components/TreeSelect/Index.vue'
import { handleTree, parseTime } from '@/utils/ruoyi'
import { ElForm, ElMessage } from 'element-plus'
export default defineComponent({
components: {
treeselect
},
setup() {
const queryForm = ref(ElForm)
const formDialog = ref(ElForm)
const dataMap = reactive({
disabled: false,
formUpdata: {} as any,
isAdd: false,
originOptions: [],
props: { // 配置项(必选)
value: 'id',
label: 'label',
children: 'children'
// disabled:true
},
loading: true,
// 显示搜索条件
showSearch: true,
// 表格树数据
deptList: [],
// 部门树选项
deptOptions: [],
// 弹出层标题
title: '',
// 是否显示弹出层
open: false,
// 状态数据字典
statusOptions: [],
// 查询参数
queryParams: {
name: undefined,
status: undefined
},
formVal: {
deptId: '',
parentId: '',
deptName: '',
orderNum: 0,
leader: '',
phone: '',
email: '',
status: ''
},
deptidfix: 0,
// 表单参数
// 表单校验
rules: {
parentId: [
{ required: true, message: '上级部门不能为空', trigger: 'blur' }
],
deptName: [
{ required: true, message: '部门名称不能为空', trigger: 'blur' }
],
orderNum: [
{ required: true, message: '显示排序不能为空', trigger: 'blur' }
],
email: [
{
type: 'email',
message: "'请输入正确的邮箱地址",
trigger: ['blur', 'change']
}
],
phone: [
{
pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
message: '请输入正确的手机号码',
trigger: 'blur'
}
]
},
test: '8347213498'
})
/** 查询部门列表 */
const getList = () => {
dataMap.loading = true
listDept(dataMap.queryParams).then((response: any) => {
console.log(response.data)
// dataMap.deptList = handleTree(response.data, 'deptId')
dataMap.deptList = response.data
dataMap.loading = false
})
}
/** 转换部门数据结构 */
const normalizer = (node: any) => {
if (node.children && !node.children.length) {
delete node.children
}
return {
id: node.deptId,
label: node.deptName,
children: node.children
}
}
// 取消按钮
const cancel = () => {
dataMap.open = false
dataMap.isAdd = false
}
/** 搜索按钮操作 */
const handleQuery = () => {
getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
const form = unref(queryForm)
form.resetFields()
handleQuery()
}
const flatten = (origin: any) => {
let result: any = []
for (let i = 0; i < origin.length; i++) {
const item = origin[i]
if (Array.isArray(item.children)) {
result = result.concat(flatten(item.children))
result.push(item)
} else {
result.push(item)
}
}
return result
}
/** 查询部门下拉树结构 */
const getTreeselect = () => {
treeselect().then(response => {
dataMap.deptOptions = response?.data
dataMap.originOptions = flatten(response?.data) as any
})
}
const handleAdd = (row: any) => {
dataMap.isAdd = true
dataMap.formVal.parentId = {} as any
if (row.deptId) {
dataMap.formVal = {} as any
dataMap.formVal.parentId = row.deptId
}
dataMap.open = true
dataMap.title = '添加部门'
}
/** 修改按钮操作 */
const handleUpdate = async(row: any) => {
dataMap.disabled = true
dataMap.isAdd = false
console.log(row.deptId)
dataMap.deptidfix = row.deptId
const result = await getDept(row.deptId)
if (result?.code === 200) {
dataMap.formUpdata = result.data
dataMap.formVal.deptName = result.data.deptName
dataMap.formVal.parentId = result.data.parentId
dataMap.formVal.orderNum = result.data.orderNum
dataMap.formVal.leader = result.data.leader
dataMap.formVal.phone = result.data.phone
dataMap.formVal.email = result.data.email
dataMap.formVal.status = result.data.status
dataMap.title = '修改部门'
dataMap.open = true
}
}
/** 提交按钮 */
const submitForm = () => {
const formNode = unref(formDialog)
formNode.validate((valid: any) => {
console.log(valid)
if (valid) {
if (!dataMap.isAdd) {
dataMap.formUpdata.parentId = dataMap.formVal.deptId
dataMap.formUpdata.deptId = dataMap.deptidfix
dataMap.formUpdata.deptName = dataMap.formVal.deptName
dataMap.formUpdata.orderNum = dataMap.formVal.orderNum
dataMap.formUpdata.leader = dataMap.formVal.leader
dataMap.formUpdata.phone = dataMap.formVal.phone
dataMap.formUpdata.email = dataMap.formVal.email
dataMap.formUpdata.status = dataMap.formVal.status
updateDept(dataMap.formUpdata).then((res: any) => {
if (res?.code === 200) {
ElMessage.success('修改成功')
dataMap.open = false
getList()
} else {
dataMap.open = false
ElMessage.error(res?.msg)
}
})
} else {
addDept(dataMap.formVal).then((res: any) => {
if (res?.code === 200) {
ElMessage.success('新增成功')
dataMap.open = false
getList()
} else {
dataMap.open = false
ElMessage.error(res?.msg)
}
})
}
}
})
}
/** 删除按钮操作 */
const handleDelete = async(row: any) => {
const result = await delDept(row.deptId)
if (result?.code === 200) {
getList()
} else {
ElMessage.error(result?.msg)
}
}
const statusFormat = (row: any) => {
return row.status === '0' ? '正常' : ' 停用'
}
const getDeptId = (e: any) => {
dataMap.formVal.deptId = e
}
const dialogshow = () => {
getTreeselect()
}
onMounted(() => {
getList()
// getTreeselect()
// getDicts('sys_normal_disable').then((response: any) => {
// dataMap.statusOptions = response.data
// })
})
return { ...toRefs(dataMap),Search,Plus,Edit,Delete,Refresh,Delete, parseTime,dialogshow, getDeptId, flatten, getTreeselect, formDialog, statusFormat, queryForm, getList, normalizer, handleDelete, cancel, handleQuery, resetQuery, handleAdd, handleUpdate, submitForm }
}
})
</script>