Vue3 树形回显+表格选择回显(记录学习)
1、主页面(可忽略)
<template>
<div class="app-container">
<el-row :gutter="20">
<el-col :span="24" :xs="24">
<el-form :model="queryParams" ref="queryRef" :inline="true" label-width="78px">
<el-form-item label="角色名称" prop="suUsername">
<el-input
v-model="queryParams.map.srName"
placeholder="请输入角色名称"
/>
</el-form-item>
<el-form-item label="角色Code" prop="suRealname">
<el-input
v-model="queryParams.map.srCode"
placeholder="请输入角色Code"
/>
</el-form-item>
<el-form-item label="公司名称" prop="companyName" v-if="proxy.$checkRole('sys_admin')">
<el-input
v-model="queryParams.map.companyName"
placeholder="请输入公司名称"
/>
</el-form-item>
<el-form-item label="更新时间" style="width: 280px;">
<el-date-picker
v-model="dateRange"
value-format="YYYY-MM-DD"
type="daterange"
range-separator="-"
start-placeholder="开始日期"
end-placeholder="结束日期"
></el-date-picker>
</el-form-item>
<el-form-item>
<el-button :color="global.btnColor" icon="Search" @click="handleQuery"
v-if="proxy.$checkAuth('SYS_RoleSelect')">搜索
</el-button>
<el-button icon="Refresh" @click="handleReset" v-if="proxy.$checkAuth('SYS_RoleReset')">重置</el-button>
</el-form-item>
</el-form>
</el-col>
</el-row>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button :color="global.btnColor" plain icon="Plus" @click="handleAdd">新增</el-button>
</el-col>
</el-row>
<!--添加或修改角色-->
<el-dialog :title="titleName" v-model="handleDialogVisible" width="500px" append-to-body>
<el-form :model="formData" :rules="rules" ref="ruleFormRef" label-width="100px">
<el-form-item label="角色名称" prop="srName">
<el-input v-model="formData.srName" clearable placeholder="请输入角色名称"/>
</el-form-item>
<el-form-item label="角色Code" prop="srCode">
<el-input v-model="formData.srCode" clearable :disabled="formData.srId != null" placeholder="请输入角色Code"/>
</el-form-item>
<el-form-item label="角色类型" prop="srType">
<el-select v-model="formData.srType" class="m-2" placeholder="请选择角色类型" clearable>
<el-option
v-for="item in typeOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</el-form-item>
<el-form-item label="所属公司" v-if="proxy.$checkRole('sys_admin')">
<el-select v-model="formData.tenantid" class="m-2" placeholder="请选择所属公司">
<el-option
v-for="item in companyTenantOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</el-form-item>
<el-form-item label="排序" prop="srSort">
<el-input-number v-model="formData.srSort" class="mx-4" :min="0"/>
</el-form-item>
<el-form-item label="是否使用" prop="srIsuse">
<el-switch v-model="formData.srIsuse"/>
</el-form-item>
<el-form-item label="备注" prop="suAddress">
<el-input v-model="formData.srNote" :rows="2" type="textarea"/>
</el-form-item>
<div class="dialog-footer" style="text-align: center">
<el-button :color="global.btnColor" @click="submitInfo(ruleFormRef)">确 定</el-button>
<el-button @click="cancelDialog(false)">取 消</el-button>
</div>
</el-form>
</el-dialog>
<div class="tbMain">
<el-table :data="roleList" border stripe style="width: 100%"
:header-cell-style="{'background-color':'#4991DD','color':'#ffffff'}" empty-text="无数据">
<el-table-column prop="srName" label="角色名称" align="center"/>
<el-table-column prop="srCode" label="角色Code" align="center"/>
<el-table-column prop="roleTypeName" label="角色类型" align="center"/>
<el-table-column prop="companyName" label="所属公司" align="center"/>
<el-table-column prop="srSort" label="排序" align="center"/>
<el-table-column prop="srNote" label="备注" align="center"/>
<el-table-column prop="srIsuse" label="是否使用" width="120" align="center">
<template #default="scope">
{{ scope.row.srIsuse ? '是' : '否' }}
</template>
</el-table-column>
<el-table-column label="操作" width="200px" align="center">
<template #default="scope">
<el-tooltip content="修改" placement="top" v-if="proxy.$checkAuth('SYS_RoleEdit')">
<el-button :color="global.btnColor" circle plain size="small" icon="Edit"
@click="handleEdit(scope.row.srId)"></el-button>
</el-tooltip>
<el-tooltip content="分配菜单" placement="top" v-if="proxy.$checkAuth('SYS_RoleAssignMenu')">
<el-button :color="global.btnColor" circle plain size="small" icon="SetUp"
@click="handleAssign(scope.row.srId)"></el-button>
</el-tooltip>
<el-tooltip content="分配权限" placement="top" v-if="proxy.$checkAuth('SYS_RoleAssignAuth')">
<el-button :color="global.btnColor" circle plain size="small" icon="CircleCheck"
@click="handleAssignAuth(scope.row.srId)"></el-button>
</el-tooltip>
<el-tooltip content="删除" placement="top" v-if="proxy.$checkAuth('SYS_RoleDelete')">
<el-button type="danger" circle plain size="small" icon="Delete"
@click="handleDelete(scope.row.srId)"></el-button>
</el-tooltip>
</template>
</el-table-column>
</el-table>
<el-pagination style="float: right;margin-top: 10px;" background layout="total, prev, pager, next"
small :current-page="curPage" :page-size="queryParams.pageSize" :total="total"
@current-change="curChange"/>
</div>
<handle-role-menu ref="handleRef" @getRoleList="getRoleList" style="height: 70%; width: 460px;overflow: hidden"
align="center"></handle-role-menu>
<handle-role-auth ref="handleAuthRef" @getRoleList="getRoleList" align="center"></handle-role-auth>
</div>
</template>
<script lang="ts" setup>
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getCurrentInstance, inject, onMounted, reactive, ref} from 'vue';
import HandleRoleMenu from './handleRoleMenu.vue';
import HandleRoleAuth from "./handleRoleAuth.vue";
const global: any = inject('global');
const roleList = ref([]);
const total = ref(0);
const handleDialogVisible = ref(false)
const titleName = ref('')
const handleRef = ref()
const handleAuthRef = ref()
const formData = ref({
srId: null,
srName: null,
srCode: null,
srType: null,
srIsuse: true,
srSort: 0,
srNote: null,
tenantid: null
})
const dateRange = ref([])
const curPage = ref(1)
const typeOptions = ref([])
const companyTenantOptions = ref([])
const {proxy} = getCurrentInstance()
const queryParams = ref({
pageNum: 1,
pageSize: 10,
map: {
srName: "",
srCode: "",
companyName: "",
srUpdateTimeStart: "",
srUpdateTimeEnd: ""
}
});
onMounted(() => {
getRoleList()
getTypeOptionsDict()
getCompanyTenantList()
});
const getTypeOptionsDict = () => {
global.axiosUtil.ajax_get(global.baseUrl + "/systemapi/sysDictionary/getDictByParentCode/" + "SYS_RoleType", function (res) {
typeOptions.value = res.data
});
}
const getCompanyTenantList = () => {
global.axiosUtil.ajax_get(global.baseUrl + "/systemapi/sysCpydept/getCompanyTenantList", function (res) {
companyTenantOptions.value = res.data
});
}
const getRoleList = () => {
global.axiosUtil.ajax_post(global.baseUrl + "/systemapi/sysRole/getRoleList", queryParams.value, function (res) {
roleList.value = res.data
total.value = res.recordsTotal
});
}
const handleAdd = () => {
handleDialogVisible.value = true
titleName.value = '添加角色'
formData.value = {
srId: null,
srName: null,
srCode: null,
srType: null,
srIsuse: true,
srSort: 0,
srNote: null,
tenantid: null
}
}
const handleEdit = (value) => {
handleDialogVisible.value = true
titleName.value = '编辑角色'
global.axiosUtil.ajax_get(global.baseUrl + "/systemapi/sysRole/getRoleDetailBySrId/" + value, function (res) {
formData.value = res.data
});
}
const handleAssign = (value) => {
handleRef.value.handleAssign(value);
}
const handleAssignAuth = (value) => {
handleAuthRef.value.handleAssignAuth(value);
}
const handleDelete = (value) => {
ElMessageBox.confirm(
'请确定是否删除当前角色数据?',
'提示',
{
confirmButtonText: '确认',
cancelButtonText: '取消',
type: 'warning',
}
).then(() => {
global.axiosUtil.ajax_get(global.baseUrl + "/systemapi/sysRole/deleteRoleBySrId/" + value, function (res) {
if (res.altStr == '1') {
ElMessage.success('删除成功!')
getRoleList()
} else {
getRoleList()
}
});
}).catch(() => {
ElMessage({
type: 'info',
message: '删除取消',
})
})
}
const handleQuery = () => {
if (dateRange.value != []) {
queryParams.value.map.srUpdateTimeStart = dateRange.value[0]
queryParams.value.map.srUpdateTimeEnd = dateRange.value[1]
}
queryParams.value.pageNum = 1;
getRoleList()
}
const handleReset = () => {
curPage.value = 1
queryParams.value.pageNum = 1;
queryParams.value.map = {
srName: "",
srCode: "",
companyName: "",
srUpdateTimeStart: "",
srUpdateTimeEnd: ""
}
dateRange.value = []
getRoleList()
}
const submitInfo = async (formEl: FormInstance | undefined) => {
if (!formEl) return
await formEl.validate((valid, fields) => {
if (valid) {
if (formData.value.srId != undefined && formData.value.srId != null) {
global.axiosUtil.ajax_post(global.baseUrl + "/systemapi/sysRole/updateRole", formData.value, function (res) {
if (res.altStr == "1") {
ElMessage.success('修改成功!')
getRoleList()
handleDialogVisible.value = false
}
});
} else {
global.axiosUtil.ajax_post(global.baseUrl + "/systemapi/sysRole/addRole", formData.value, function (res) {
if (res.altStr == "-1") {
ElMessage.error('角色Code只能唯一!')
} else if (res.altStr == "1") {
ElMessage.success('添加成功!')
getRoleList()
handleDialogVisible.value = false
}
});
}
} else {
ElMessage.error('请输入正确后再提交信息!')
}
})
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
srName: [
{required: true, message: '请输入角色名称', trigger: 'blur'},
{min: 3, max: 18, message: '长度在3到18位', trigger: 'blur'},
],
srCode: [
{required: true, message: '请输入角色Code', trigger: 'blur'},
{min: 3, max: 18, message: '长度在3到18位', trigger: 'blur'},
],
srSort: [
{required: true, message: '请输入排序', trigger: 'blur'},
],
})
const curChange = (currentPage) => {
curPage.value = currentPage
if (curPage.value == 1) {
queryParams.value.pageNum = 0
} else {
queryParams.value.pageNum = (curPage.value - 1) * queryParams.value.pageSize
}
getRoleList()
}
const cancelDialog = (value) => {
handleDialogVisible.value = value
formData.value = {
srId: null,
srName: null,
srCode: null,
srType: null,
srIsuse: true,
srSort: 0,
srNote: null,
tenantid: null
}
ruleFormRef.value.clearValidate()
}
</script>
<style>
.tbMain {
margin-top: 8px;
}
</style>
2、树形回显
<template>
<el-dialog v-model="handleDialogVisible" :title="titleName" destroy-on-close draggable :close-on-click-modal="false">
<el-row>
<el-col :span="12" style="float: left;margin-left: 95px">
<el-input v-model="filterText" placeholder="输入关键字进行过滤" />
</el-col>
</el-row>
<el-row>
<el-col :span="15" style="float: left;margin-left: 95px">
<el-tree :data="treeData" :default-checked-keys="selectTreeArr"
node-key="value" ref="tree" :filter-node-method="filterNode"
:props="defaultProps" :show-checkbox="true" :default-expand-all="true"/>
</el-col>
</el-row>
<div style="position: absolute;right: 20px;bottom:20px">
<el-button :color="global.btnColor" @click="submitInfo">确 定</el-button>
<el-button @click="cancelDialog(false)">取 消</el-button>
</div>
</el-dialog>
</template>
<script lang="ts" setup>
import {ref, reactive, inject, onMounted, toRefs, defineProps, defineExpose, Ref, watch} from 'vue';
import type { FormInstance, FormRules} from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
const global:any = inject('global');
const emit = defineEmits(['getRoleList'])
const handleDialogVisible = ref(false);
const treeData = ref([])
const titleName = ref('');
const menuIds = ref('')
const selectTreeArr = ref([])
const roleId = ref()
const tree:Ref = ref(null);
const filterText = ref('')
const defaultProps = ref({
children: 'children',
label: 'label'
})
interface Tree {
value: number
label: string
children?: Tree[]
}
watch(filterText, (val) => {
tree.value!.filter(val)
})
const filterNode = (value: string, data: Tree) => {
if (!value) return true
return data.label.includes(value)
}
const unique = (arr)=>{
let newArr = []
let len = arr.length
for (let i=0;i<len;i++){
if(newArr.indexOf(arr[i])==-1){
newArr.push(arr[i])
}
}
return newArr
}
const treeToList =(node,arr)=>{
for(let item of node){
arr.push(item.value)
if(item.children && item.children.length){
treeToList(item.children,arr)
}
}
return arr
}
const handleAssign = (value)=>{
handleDialogVisible.value = true
titleName.value = '分配菜单'
roleId.value = value
global.axiosUtil.ajax_get(global.baseUrl + "/systemapi/sysRolemenu/getRoleMenuData/"+roleId.value,function(res){
if(res.altStr == "1"){
res.data.forEach(function (item){
tree.value.setChecked(item,true,false)
})
}else if(res.altStr == "0"){
ElMessage.success('请配置角色菜单!')
}
});
}
const getMenuOptions =()=>{
global.axiosUtil.ajax_get(global.baseUrl + "/systemapi/sysMenu/getMenuCodeDownList",function(res){
treeData.value = res.data;
});
}
onMounted(()=>{
getMenuOptions()
});
const submitInfo = ()=>{
const arr = tree.value.getCheckedNodes(false,true)
const list = []
arr.forEach(item=>{
list.push(item.value)
})
menuIds.value = list.join(",")
const map = {
"srId": roleId.value,
"menuIds": menuIds.value
}
if(roleId.value != undefined && roleId.value != null){
global.axiosUtil.ajax_post(global.baseUrl + "/systemapi/sysRolemenu/batchHandleRoleMenu",map,function(res){
if(res.altStr == "1"){
ElMessage.success('分配成功!')
emit("getRoleList");
handleDialogVisible.value = false
}else if(res.altStr == "-1"){
ElMessage.error('当前操作无修改!')
handleDialogVisible.value = false
}else if(res.altStr == "2"){
ElMessage.success('已清空所有角色菜单关系数据!')
emit("getRoleList");
handleDialogVisible.value = false
}
});
}
};
const cancelDialog = (value:boolean)=>{
handleDialogVisible.value = value
menuIds.value = ''
tree.value = null
}
defineExpose({
handleDialogVisible,
handleAssign,
cancelDialog
});
</script>
<style scoped>
</style>
3、表格选择回显
<template>
<el-dialog v-model="handleDialogVisible" :title="titleName" destroy-on-close draggable :close-on-click-modal="false">
<div class="tbMain">
<el-table :data="authList" border stripe style="width: 100%;overflow-y: auto" max-height="400px"
@selection-change="selectionChangeHandle" ref="dataTable"
:header-cell-style="{'background-color':'#94a7c8','color':'#ffffff'}" empty-text="无数据">
<el-table-column type="selection" width="55" align="center"/>
<el-table-column prop="saName" label="权限名称" align="center"/>
<el-table-column prop="saCode" label="权限Code" align="center"/>
<el-table-column prop="menuName" label="所属菜单" align="center"/>
</el-table>
</div>
<template #footer>
<span class="dialog-footer">
<el-button :color="global.btnColor" @click="submitInfo">确 定</el-button>
<el-button @click="cancelDialog(false)">取 消</el-button>
</span>
</template>
</el-dialog>
</template>
<script lang="ts" setup>
import {ref, reactive, inject, onMounted, toRefs, defineProps, defineExpose, Ref} from 'vue';
import type { FormInstance, FormRules} from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
const global:any = inject('global');
const emit = defineEmits(['getRoleList'])
const handleDialogVisible = ref(false);
const titleName = ref('');
const authIds = ref('')
const selectIdArr = ref([])
const selectData = ref([])
const roleId = ref()
const authList = ref([])
const dataTable:Ref = ref(null)
const map = ref({
srId: '',
saName: '',
saSmId: ''
})
const handleQuery = ()=>{
getRoleAuthList(map.value)
}
const getRoleAuthList =(data)=>{
global.axiosUtil.ajax_post(global.baseUrl + "/systemapi/sysAuth/getRoleAuthList",data,function(res){
if(res.altStr == "1"){
authList.value = res.data
global.axiosUtil.ajax_get(global.baseUrl + "/systemapi/sysAuth/getCheckAuthData/"+data.srId,function(res){
if(res.altStr == "1"){
let list = []
authList.value.forEach((item)=>{
res.data.forEach((val)=>{
if(item.saId === val.saId){
list.push(item)
}
})
})
if(list){
list.forEach((row)=>{
dataTable.value.toggleRowSelection(row, true)
})
}
}
})
}else if(res.altStr == "-1"){
ElMessage.info('当前角色无权限可分配!')
}else if(res.altStr == "0"){
ElMessage.success('当前传入角色Id为空!查询失败')
emit("getRoleList");
handleDialogVisible.value = false
}else if(res.altStr == "-2"){
ElMessage.info('查询报错!')
}
});
}
const selectionChangeHandle = (val) =>{
selectData.value = val
}
const handleAssignAuth = (value)=>{
handleDialogVisible.value = true
titleName.value = '分配权限'
map.value.srId = value
roleId.value = value
getRoleAuthList(map.value)
}
const menuOptions = ref([])
onMounted(()=>{
global.axiosUtil.ajax_get(global.baseUrl + "/systemapi/sysMenu/getMenuDownList", function (res) {
menuOptions.value = res.data;
});
});
const submitInfo = ()=>{
selectData.value.forEach((item)=>{
selectIdArr.value.push(item.saId)
})
authIds.value = selectIdArr.value.join(",")
const data = {
"srId": roleId.value,
"authIds": authIds.value
}
if(roleId.value != undefined && roleId.value != null){
global.axiosUtil.ajax_post(global.baseUrl + "/systemapi/sysRoleauth/batchHandleRoleAuth",data,function(res){
if(res.altStr == "1"){
ElMessage.success('分配成功!')
getRoleAuthList(map.value)
emit("getRoleList");
handleDialogVisible.value = false
}else if(res.altStr == "-1"){
ElMessage.error('当前操作无修改!')
handleDialogVisible.value = false
}else if(res.altStr == "2"){
ElMessage.success('已清空所有角色权限关系数据!')
emit("getRoleList");
handleDialogVisible.value = false
}
});
}
};
const cancelDialog = (value:boolean)=>{
handleDialogVisible.value = value
selectData.value = []
selectIdArr.value = []
authList.value = []
authIds.value = ''
}
defineExpose({
handleDialogVisible,
handleAssignAuth,
cancelDialog
});
</script>
<style scoped>
</style>