提交 e221f9f6 authored 作者: hejie's avatar hejie

feat: 系统管理-角色管理列表和新增联调

上级 8d3cd969
import { http } from "@/utils/http";
type Result = {
success: boolean;
data?: Array<any>;
code?: string;
msg?: string;
status?: number;
};
type ResultTable = {
success: boolean;
records?: {
/** 列表数据 */
list: Array<any>;
/** 总条目数 */
total?: number;
/** 每页显示条目个数 */
pageSize?: number;
/** 当前页数 */
currentPage?: number;
};
};
/** 获取系统管理-角色管理列表 */
export const getRoleList = (data?: object) => {
// return http.request<ResultTable>("post", "/role", { data });
return http.request<ResultTable>("post", "/api/role/find-role-list-by-page", {
data
});
};
// 系统管理-删除角色
export const deleteRole = (data?: { id: string }) => {
return http.request<Result>("post", "/api/role/delete-role", { data });
};
// 系统管理-添加角色
export const addRole = (data?: object) => {
return http.request<Result>("post", "/api/role/add-role", { data });
};
// 系统管理-修改角色
export const updateRole = (data?: object) => {
return http.request<Result>("post", "/api/role/update-role", { data });
};
// 抽离可公用的工具函数等用于系统管理页面逻辑
import { computed } from "vue";
import { useDark } from "@pureadmin/utils";
export function usePublicHooks() {
const { isDark } = useDark();
const switchStyle = computed(() => {
return {
"--el-switch-on-color": "#6abe39",
"--el-switch-off-color": "#e84749"
};
});
const tagStyle = computed(() => {
return (status: number) => {
return status === 1
? {
"--el-tag-text-color": isDark.value ? "#6abe39" : "#389e0d",
"--el-tag-bg-color": isDark.value ? "#172412" : "#f6ffed",
"--el-tag-border-color": isDark.value ? "#274a17" : "#b7eb8f"
}
: {
"--el-tag-text-color": isDark.value ? "#e84749" : "#cf1322",
"--el-tag-bg-color": isDark.value ? "#2b1316" : "#fff1f0",
"--el-tag-border-color": isDark.value ? "#58191c" : "#ffa39e"
};
};
});
return {
/** 当前网页是否为`dark`模式 */
isDark,
/** 表现更鲜明的`el-switch`组件 */
switchStyle,
/** 表现更鲜明的`el-tag`组件 */
tagStyle
};
}
<script setup lang="ts">
import { ref } from "vue";
import { formRules } from "./utils/rule";
import { FormProps } from "./utils/types";
const props = withDefaults(defineProps<FormProps>(), {
formInline: () => ({
name: "",
code: "",
remark: ""
})
});
const ruleFormRef = ref();
const newFormInline = ref(props.formInline);
function getRef() {
return ruleFormRef.value;
}
defineExpose({ getRef });
</script>
<template>
<el-form
ref="ruleFormRef"
:model="newFormInline"
:rules="formRules"
label-width="82px"
>
<el-form-item label="角色名称" prop="name">
<el-input
v-model="newFormInline.name"
clearable
placeholder="请输入角色名称"
/>
</el-form-item>
<el-form-item label="角色标识" prop="code">
<el-input
v-model="newFormInline.code"
clearable
placeholder="请输入角色标识"
/>
</el-form-item>
<el-form-item label="备注">
<el-input
v-model="newFormInline.remark"
placeholder="请输入备注信息"
type="textarea"
/>
</el-form-item>
</el-form>
</template>
<script setup lang="ts">
import { useRole } from "./utils/hook";
import { ref, computed, nextTick, onMounted } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
delay,
subBefore,
deviceDetection,
useResizeObserver
} from "@pureadmin/utils";
// import Database from "~icons/ri/database-2-line";
// import More from "~icons/ep/more-filled";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import Menu from "~icons/ep/menu";
import AddFill from "~icons/ri/add-circle-line";
import Close from "~icons/ep/close";
import Check from "~icons/ep/check";
defineOptions({
name: "SystemRole"
});
const iconClass = computed(() => {
return [
"w-[22px]",
"h-[22px]",
"flex",
"justify-center",
"items-center",
"outline-hidden",
"rounded-[4px]",
"cursor-pointer",
"transition-colors",
"hover:bg-[#0000000f]",
"dark:hover:bg-[#ffffff1f]",
"dark:hover:text-[#ffffffd9]"
];
});
const treeRef = ref();
const formRef = ref();
const tableRef = ref();
const contentRef = ref();
const treeHeight = ref();
const {
form,
isShow,
curRow,
loading,
columns,
rowStyle,
dataList,
treeData,
treeProps,
isLinkage,
pagination,
isExpandAll,
isSelectAll,
treeSearchValue,
// buttonClass,
onSearch,
resetForm,
openDialog,
handleMenu,
handleSave,
handleDelete,
filterMethod,
transformI18n,
onQueryChanged,
// handleDatabase,
handleSizeChange,
handleCurrentChange,
handleSelectionChange
} = useRole(treeRef);
onMounted(() => {
useResizeObserver(contentRef, async () => {
await nextTick();
delay(60).then(() => {
treeHeight.value = parseFloat(
subBefore(tableRef.value.getTableDoms().tableWrapper.style.height, "px")
);
});
});
});
</script>
<template>
<div class="systems">
<h2>Systems</h2>
<slot />
<div class="main">
<el-form
ref="formRef"
:inline="true"
:model="form"
class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
>
<el-form-item label="角色名称:" prop="name">
<el-input
v-model="form.name"
placeholder="请输入角色名称"
clearable
class="w-[180px]!"
/>
</el-form-item>
<el-form-item label="角色标识:" prop="code">
<el-input
v-model="form.code"
placeholder="请输入角色标识"
clearable
class="w-[180px]!"
/>
</el-form-item>
<el-form-item label="状态:" prop="status">
<el-select
v-model="form.status"
placeholder="请选择状态"
clearable
class="w-[180px]!"
>
<el-option label="已启用" value="1" />
<el-option label="已停用" value="0" />
</el-select>
</el-form-item>
<el-form-item>
<el-button
type="primary"
:icon="useRenderIcon('ri/search-line')"
:loading="loading"
@click="onSearch"
>
搜索
</el-button>
<el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
重置
</el-button>
</el-form-item>
</el-form>
<div
ref="contentRef"
:class="['flex', deviceDetection() ? 'flex-wrap' : '']"
>
<PureTableBar
:class="[isShow && !deviceDetection() ? 'w-[60vw]!' : 'w-full']"
style="transition: width 220ms cubic-bezier(0.4, 0, 0.2, 1)"
title="角色管理(仅演示,操作后不生效)"
:columns="columns"
@refresh="onSearch"
>
<template #buttons>
<el-button
type="primary"
:icon="useRenderIcon(AddFill)"
@click="openDialog()"
>
新增角色
</el-button>
</template>
<template v-slot="{ size, dynamicColumns }">
<pure-table
ref="tableRef"
align-whole="center"
showOverflowTooltip
table-layout="auto"
:loading="loading"
:size="size"
adaptive
:row-style="rowStyle"
:adaptiveConfig="{ offsetBottom: 108 }"
:data="dataList"
:columns="dynamicColumns"
:pagination="{ ...pagination, size }"
:header-cell-style="{
background: 'var(--el-fill-color-light)',
color: 'var(--el-text-color-primary)'
}"
@selection-change="handleSelectionChange"
@page-size-change="handleSizeChange"
@page-current-change="handleCurrentChange"
>
<template #operation="{ row }">
<el-button
class="reset-margin"
link
type="primary"
:size="size"
:icon="useRenderIcon(EditPen)"
@click="openDialog('修改', row)"
>
修改
</el-button>
<el-popconfirm
:title="`是否确认删除角色名称为${row.name}的这条数据`"
@confirm="handleDelete(row)"
>
<template #reference>
<el-button
class="reset-margin"
link
type="primary"
:size="size"
:icon="useRenderIcon(Delete)"
>
删除
</el-button>
</template>
</el-popconfirm>
<el-button
class="reset-margin"
link
type="primary"
:size="size"
:icon="useRenderIcon(Menu)"
@click="handleMenu(row)"
>
权限
</el-button>
<!-- <el-dropdown>
<el-button
class="ml-3 mt-[2px]"
link
type="primary"
:size="size"
:icon="useRenderIcon(More)"
/>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item>
<el-button
:class="buttonClass"
link
type="primary"
:size="size"
:icon="useRenderIcon(Menu)"
@click="handleMenu"
>
菜单权限
</el-button>
</el-dropdown-item>
<el-dropdown-item>
<el-button
:class="buttonClass"
link
type="primary"
:size="size"
:icon="useRenderIcon(Database)"
@click="handleDatabase"
>
数据权限
</el-button>
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown> -->
</template>
</pure-table>
</template>
</PureTableBar>
<div
v-if="isShow"
class="min-w-[calc(100vw-60vw-268px)]! w-full mt-2 px-2 pb-2 bg-bg_color ml-2 overflow-auto"
>
<div class="flex justify-between w-full px-3 pt-5 pb-4">
<div class="flex">
<span :class="iconClass">
<IconifyIconOffline
v-tippy="{
content: '关闭'
}"
class="dark:text-white"
width="18px"
height="18px"
:icon="Close"
@click="handleMenu"
/>
</span>
<span :class="[iconClass, 'ml-2']">
<IconifyIconOffline
v-tippy="{
content: '保存菜单权限'
}"
class="dark:text-white"
width="18px"
height="18px"
:icon="Check"
@click="handleSave"
/>
</span>
</div>
<p class="font-bold truncate">
菜单权限
{{ `${curRow?.name ? `(${curRow.name})` : ""}` }}
</p>
</div>
<el-input
v-model="treeSearchValue"
placeholder="请输入菜单进行搜索"
class="mb-1"
clearable
@input="onQueryChanged"
/>
<div class="flex flex-wrap">
<el-checkbox v-model="isExpandAll" label="展开/折叠" />
<el-checkbox v-model="isSelectAll" label="全选/全不选" />
<el-checkbox v-model="isLinkage" label="父子联动" />
</div>
<el-tree-v2
ref="treeRef"
show-checkbox
:data="treeData"
:props="treeProps"
:height="treeHeight"
:check-strictly="!isLinkage"
:filter-method="filterMethod"
>
<template #default="{ node }">
<span>{{ transformI18n(node.label) }}</span>
</template>
</el-tree-v2>
</div>
</div>
</div>
</template>
<script setup lang="ts">
// 组件逻辑部分
import { ref } from "vue";
const count = ref(0);
<style lang="scss" scoped>
:deep(.el-dropdown-menu__item i) {
margin: 0;
}
const increment = () => {
count.value++;
};
</script>
.main-content {
margin: 24px 24px 0 !important;
}
<style scoped lang="scss">
.systems {
padding: 20px;
border: 1px solid #ccc;
.search-form {
:deep(.el-form-item) {
margin-bottom: 12px;
}
}
</style>
import dayjs from "dayjs";
import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import { getRoleMenu, getRoleMenuIds } from "@/api/system";
import { getRoleList, addRole, updateRole } from "@/api/role";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";
export function useRole(treeRef: Ref) {
const form = reactive({
// name: "",
// code: "",
// status: ""
pageNum: 1,
pageSize: 10
});
const curRow = ref();
const formRef = ref();
const dataList = ref([]);
const treeIds = ref([]);
const treeData = ref([]);
const isShow = ref(false);
const loading = ref(true);
const isLinkage = ref(false);
const treeSearchValue = ref();
const switchLoadMap = ref({});
const isExpandAll = ref(false);
const isSelectAll = ref(false);
const { switchStyle } = usePublicHooks();
const treeProps = {
value: "id",
label: "title",
children: "children"
};
const pagination = reactive<PaginationProps>({
total: 0,
pageSize: 10,
currentPage: 1,
background: true
});
const columns: TableColumnList = [
{
label: "角色编号",
prop: "id"
},
{
label: "角色名称",
prop: "name"
},
{
label: "角色标识",
prop: "code"
},
{
label: "状态",
cellRenderer: scope => (
<el-switch
size={scope.props.size === "small" ? "small" : "default"}
loading={switchLoadMap.value[scope.index]?.loading}
v-model={scope.row.status}
active-value={1}
inactive-value={0}
active-text="已启用"
inactive-text="已停用"
inline-prompt
style={switchStyle.value}
onChange={() => onChange(scope as any)}
/>
),
minWidth: 90
},
{
label: "备注",
prop: "remark",
minWidth: 160
},
{
label: "创建时间",
prop: "createTime",
minWidth: 160,
formatter: ({ createTime }) =>
dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
},
{
label: "操作",
fixed: "right",
width: 210,
slot: "operation"
}
];
// const buttonClass = computed(() => {
// return [
// "h-[20px]!",
// "reset-margin",
// "text-gray-500!",
// "dark:text-white!",
// "dark:hover:text-primary!"
// ];
// });
function onChange({ row, index }) {
ElMessageBox.confirm(
`确认要<strong>${
row.status === 0 ? "停用" : "启用"
}</strong><strong style='color:var(--el-color-primary)'>${
row.name
}</strong>吗?`,
"系统提示",
{
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
dangerouslyUseHTMLString: true,
draggable: true
}
)
.then(() => {
switchLoadMap.value[index] = Object.assign(
{},
switchLoadMap.value[index],
{
loading: true
}
);
setTimeout(() => {
switchLoadMap.value[index] = Object.assign(
{},
switchLoadMap.value[index],
{
loading: false
}
);
message(`已${row.status === 0 ? "停用" : "启用"}${row.name}`, {
type: "success"
});
}, 300);
})
.catch(() => {
row.status === 0 ? (row.status = 1) : (row.status = 0);
});
}
function handleDelete(row) {
message(`您删除了角色名称为${row.name}的这条数据`, { type: "success" });
onSearch();
}
function handleSizeChange(val: number) {
console.log(`${val} items per page`);
}
function handleCurrentChange(val: number) {
console.log(`current page: ${val}`);
}
function handleSelectionChange(val) {
console.log("handleSelectionChange", val);
}
async function onSearch() {
loading.value = true;
const { data } = await getRoleList(toRaw(form));
dataList.value = data.records;
pagination.total = data.total;
pagination.pageSize = data.pageSize;
pagination.currentPage = data.currentPage;
setTimeout(() => {
loading.value = false;
}, 500);
}
const resetForm = formEl => {
if (!formEl) return;
formEl.resetFields();
onSearch();
};
function openDialog(title = "新增", row?: FormItemProps) {
addDialog({
title: `${title}角色`,
props: {
formInline: {
name: row?.name ?? "",
code: row?.code ?? "",
remark: row?.remark ?? ""
}
},
width: "40%",
draggable: true,
fullscreen: deviceDetection(),
fullscreenIcon: true,
closeOnClickModal: false,
contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
beforeSure: (done, { options }) => {
const FormRef = formRef.value.getRef();
const curData = options.props.formInline as FormItemProps;
function chores() {
message(`您${title}了角色名称为${curData.name}的这条数据`, {
type: "success"
});
done(); // 关闭弹框
onSearch(); // 刷新表格数据
}
FormRef.validate(valid => {
if (valid) {
console.log("curData", curData);
// 表单规则校验通过
if (title === "新增") {
addRole(curData).then(res => {
if (res.code === "0") {
message(`角色名称为${curData.name}的新增成功`, {
type: "success"
});
// 实际开发先调用新增接口,再进行下面操作
chores();
}
});
// 实际开发先调用新增接口,再进行下面操作
// chores();
} else {
// 实际开发先调用修改接口,再进行下面操作
// chores();
updateRole(curData).then(res => {
if (res.code === "0") {
message(`角色名称为${curData.name}的新增成功`, {
type: "success"
});
// 实际开发先调用新增接口,再进行下面操作
chores();
}
});
}
}
});
}
});
}
/** 菜单权限 */
async function handleMenu(row?: any) {
const { id } = row;
if (id) {
curRow.value = row;
isShow.value = true;
const { data } = await getRoleMenuIds({ id });
treeRef.value.setCheckedKeys(data);
} else {
curRow.value = null;
isShow.value = false;
}
}
/** 高亮当前权限选中行 */
function rowStyle({ row: { id } }) {
return {
cursor: "pointer",
background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
};
}
/** 菜单权限-保存 */
function handleSave() {
const { id, name } = curRow.value;
// 根据用户 id 调用实际项目中菜单权限修改接口
console.log(id, treeRef.value.getCheckedKeys());
message(`角色名称为${name}的菜单权限修改成功`, {
type: "success"
});
}
/** 数据权限 可自行开发 */
// function handleDatabase() {}
const onQueryChanged = (query: string) => {
treeRef.value!.filter(query);
};
const filterMethod = (query: string, node) => {
return transformI18n(node.title)!.includes(query);
};
onMounted(async () => {
onSearch();
const { data } = await getRoleMenu();
treeIds.value = getKeyList(data, "id");
treeData.value = handleTree(data);
});
watch(isExpandAll, val => {
val
? treeRef.value.setExpandedKeys(treeIds.value)
: treeRef.value.setExpandedKeys([]);
});
watch(isSelectAll, val => {
val
? treeRef.value.setCheckedKeys(treeIds.value)
: treeRef.value.setCheckedKeys([]);
});
return {
form,
isShow,
curRow,
loading,
columns,
rowStyle,
dataList,
treeData,
treeProps,
isLinkage,
pagination,
isExpandAll,
isSelectAll,
treeSearchValue,
// buttonClass,
onSearch,
resetForm,
openDialog,
handleMenu,
handleSave,
handleDelete,
filterMethod,
transformI18n,
onQueryChanged,
// handleDatabase,
handleSizeChange,
handleCurrentChange,
handleSelectionChange
};
}
import { reactive } from "vue";
import type { FormRules } from "element-plus";
/** 自定义表单规则校验 */
export const formRules = reactive(<FormRules>{
name: [{ required: true, message: "角色名称为必填项", trigger: "blur" }],
code: [{ required: true, message: "角色标识为必填项", trigger: "blur" }]
});
// 虽然字段很少 但是抽离出来 后续有扩展字段需求就很方便了
interface FormItemProps {
/** 角色名称 */
name: string;
/** 角色编号 */
code: string;
/** 备注 */
remark: string;
}
interface FormProps {
formInline: FormItemProps;
}
export type { FormItemProps, FormProps };
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论