chore: 完善切换租户组件

This commit is contained in:
AN
2025-04-26 13:07:34 +08:00
parent 15acc1ff68
commit 28c88c485f
6 changed files with 138 additions and 34 deletions

View File

@ -1,17 +1,60 @@
<script setup lang="ts">
import { ref } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import type { SelectOption } from 'naive-ui';
import { useLoading } from '@sa/hooks';
import { fetchTenantList } from '@/service/api';
import { fetchChangeTenant, fetchClearTenant } from '@/service/api/system/tenant';
import { useTabStore } from '@/store/modules/tab';
import { useAuth } from '@/hooks/business/auth';
const { hasRole } = useAuth();
const { clearTabs } = useTabStore();
const router = useRouter();
defineOptions({ name: 'TenantSelect' });
const value = defineModel<CommonType.IdType>('value', { required: false, default: '000000' });
const enabled = defineModel<boolean>('enabled', { required: false, default: false });
interface Props {
clearable?: boolean;
}
withDefaults(defineProps<Props>(), {
clearable: false
});
const tenantId = defineModel<CommonType.IdType>('tenantId', { required: false, default: undefined });
const enabled = defineModel<boolean>('enabled', { required: false, default: true });
const lastSelected = ref<CommonType.IdType>();
const tenantOption = ref<SelectOption[]>([]);
const { loading, startLoading, endLoading } = useLoading();
const showTenantSelect = computed<boolean>(() => {
return hasRole('superadmin') && enabled.value;
});
async function handleChangeTenant(_tenantId: CommonType.IdType) {
if (!_tenantId) {
return;
}
if (lastSelected.value === _tenantId) {
return;
}
await fetchChangeTenant(_tenantId);
lastSelected.value = _tenantId;
window.$message?.success('切换租户成功');
clearTabs();
router.push('/');
}
async function handleClearTenant() {
await fetchClearTenant();
lastSelected.value = '';
window.$message?.success('切换为默认租户');
clearTabs();
router.push('/');
}
async function handleFetchTenantList() {
startLoading();
const { data, error } = await fetchTenantList();
@ -25,16 +68,23 @@ async function handleFetchTenantList() {
});
endLoading();
}
handleFetchTenantList();
onMounted(async () => {
if (!hasRole('superadmin')) {
return;
}
await handleFetchTenantList();
});
</script>
<template>
<NSelect
v-if="enabled"
v-model:value="value"
placeholder="请选择/输入公司名称"
v-if="showTenantSelect"
v-model:value="tenantId"
:clearable="clearable"
placeholder="请选择租户"
:options="tenantOption"
:loading="loading"
@update:value="handleChangeTenant"
@clear="handleClearTenant"
/>
</template>