feat: add SingleRecordMnt component for student record maintenance with search, add, edit, view, and delete functionalities

This commit is contained in:
skytek_xinliang
2026-03-26 11:24:37 +08:00
parent 507afcc99c
commit 069141794e
116 changed files with 15247 additions and 107 deletions
+81
View File
@@ -0,0 +1,81 @@
<template>
<SKAnalysis
:bar-data="barData"
:chart1-title="chart1Title"
:chart2-title="chart2Title"
:chart3-title="chart3Title"
:pie1-data="pie1Data"
:pie2-data="pie2Data"
:stats="stats"
:trend-data="trendData"
:trend-title="trendTitle"
/>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import SKAnalysis from '@/components/SKAnalysis.vue'
// Mock Data
const stats = ref([
{
title: '學生總數',
value: '2,580',
icon: 'mdi-account-school',
color: 'primary',
label: '總學籍人數',
total: '120,000',
},
{
title: '平台訪問',
value: '20,000',
icon: 'mdi-chart-pie',
color: 'error',
label: '今日訪問量',
total: '500,000',
},
{
title: '教材下載',
value: '8,000',
icon: 'mdi-cloud-download',
color: 'warning',
label: '本月下載次數',
total: '120,000',
},
{
title: '圖書館借閱',
value: '5,000',
icon: 'mdi-book-open-page-variant',
color: 'success',
label: '總借閱量',
total: '50,000',
},
])
const trendTitle = ref('數位學習平台流量')
const trendData = ref([0, 2, 5, 9, 5, 10, 3, 5, 0, 0, 1, 8, 2, 9, 0])
const chart1Title = ref('學生核心素養指標 (平均)')
const barData = ref([
{ label: '道德實踐 (Moral)', value: 85, color: 'info' },
{ label: '智力發展 (Intellectual)', value: 72, color: 'success' },
{ label: '體育健康 (Physical)', value: 90, color: 'warning' },
{ label: '群育合作 (Social)', value: 65, color: 'error' },
{ label: '美感教育 (Aesthetic)', value: 80, color: 'primary' },
])
const chart2Title = ref('訪問裝置來源')
const pie1Data = ref({
value: 75,
label: '行動裝置',
color: 'purple-accent-2',
})
const chart3Title = ref('本學期及格率')
const pie2Data = ref({
value: 92,
label: '全校平均',
color: 'teal-lighten-1',
icon: 'mdi-check-decagram',
})
</script>
+118
View File
@@ -0,0 +1,118 @@
<template>
<SKDashboard
:announcements="announcements"
:applications="applications"
:greeting-title="greetingTitle"
:quick-navs="quickNavs"
:todos="todos"
:user-avatar="userAvatar"
/>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import SKDashboard from '@/components/SKDashboard.vue'
const userAvatar = ref(
'https://avataaars.io/?avatarStyle=Circle&topType=ShortHairShortFlat&accessoriesType=Sunglasses&hairColor=Black&facialHairType=Blank&clotheType=BlazerShirt&clotheColor=Blue01&eyeType=Happy&eyebrowType=Default&mouthType=Smile&skinColor=Light'
)
const greetingTitle = ref('早安,王校長,開始您一天的工作吧!')
const applications = ref([
{
name: '校務行政系統',
icon: 'mdi-school',
desc: '全校教職員工生學籍資料、人事資料、財產管理等核心系統入口。',
group: '行政組',
date: '2025-01-05',
color: 'primary',
},
{
name: '數位學習平台',
icon: 'mdi-monitor-shimmer',
desc: '提供線上課程、作業繳交、測驗評量與師生互動討論功能。',
group: '教學組',
date: '2025-01-02',
color: 'success',
},
{
name: '圖書館系統',
icon: 'mdi-book-open-variant',
desc: '館藏查詢、圖書借閱、還書預約與電子書資源整合平台。',
group: '圖書館',
date: '2024-12-28',
color: 'warning',
},
{
name: '學生請假系統',
icon: 'mdi-calendar-check',
desc: '學生線上請假申請、導師審核、生輔組備查流程電子化。',
group: '學務處',
date: '2024-12-25',
color: 'error',
},
{
name: '報修系統',
icon: 'mdi-hammer-wrench',
desc: '校園設施設備故障通報、維修進度查詢與滿意度調查。',
group: '總務處',
date: '2024-12-20',
color: 'purple',
},
{
name: '會議室預約',
icon: 'mdi-account-group',
desc: '校內各大型會議室、視聽教室場地查詢與線上預約登記。',
group: '總務處',
date: '2024-12-15',
color: 'teal',
},
])
const announcements = ref([
{
title: '發布全校停課通知 (凱米颱風)',
author: '教務處',
time: '1 小時前',
avatarColor: 'error',
avatarSrc: null,
},
{
title: '發布 113 學年度行事曆',
author: '王校長',
time: '2 天前',
avatarColor: 'primary',
avatarSrc: userAvatar.value,
},
{
title: '回覆關於營養午餐的建議',
author: '總務主任',
time: '3 天前',
avatarColor: 'warning',
avatarSrc: null,
},
{
title: '更新校園防疫規定',
author: '衛生組長',
time: '1 週前',
avatarColor: 'success',
avatarSrc: null,
},
])
const quickNavs = ref([
{ title: '首頁', icon: 'mdi-home', color: 'primary' },
{ title: '控制台', icon: 'mdi-view-dashboard', color: 'error' },
{ title: '組件', icon: 'mdi-layers', color: 'warning' },
{ title: '系統管理', icon: 'mdi-cog', color: 'success' },
{ title: '權限', icon: 'mdi-lock', color: 'purple' },
{ title: '圖表', icon: 'mdi-chart-bar', color: 'info' },
])
const todos = ref([
{ title: '審查期末考題', due: '今天 11:00', done: false },
{ title: '簽核採購申請單', due: '今天 14:00', done: false },
{ title: '校務會議', due: '明天 09:00', done: false },
{ title: '教學巡堂', due: '週五 10:00', done: true },
])
</script>
+188
View File
@@ -0,0 +1,188 @@
<template>
<SKDeptManagement
:items="deptItems"
:loading="loading"
:status-options="statusOptions"
@add-sub="onAddSub"
@create="onCreate"
@delete="onDelete"
@edit="onEdit"
/>
</template>
<script setup lang="ts">
import type { DeptItem } from '@/components/SKDeptManagement.vue'
import { ref } from 'vue'
import SKDeptManagement from '@/components/SKDeptManagement.vue'
const loading = ref(false)
const statusOptions = [
{ title: '已啟用', value: 1 },
{ title: '已禁用', value: 0 },
]
const deptItems = ref([
{
id: 1,
name: '校長室',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '負責統籌全校校務發展',
children: [],
},
{
id: 2,
name: '教務處',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '負責課程教學與學籍管理',
children: [
{
id: 21,
name: '教學組',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '課程編排、教師授課與教學評鑑',
children: [],
},
{
id: 22,
name: '註冊組',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '學生學籍管理、成績處理與升學輔導',
children: [],
},
{
id: 23,
name: '設備組',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '教學設備採購與維護',
children: [],
},
],
},
{
id: 3,
name: '學務處',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '負責學生生活輔導與活動規劃',
children: [
{
id: 31,
name: '訓育組',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '學生自治活動、社團活動與校慶規劃',
children: [],
},
{
id: 32,
name: '生輔組',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '學生生活常規、出缺席管理與校園安全',
children: [],
},
{
id: 33,
name: '衛生組',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '校園環境衛生、傳染病防治與健康促進',
children: [],
},
],
},
{
id: 4,
name: '總務處',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '負責校園營繕、財產管理與經費出納',
children: [
{
id: 41,
name: '庶務組',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '校舍修繕、物品採購與工友管理',
children: [],
},
{
id: 42,
name: '出納組',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '現金出納、薪津發放與學費收繳',
children: [],
},
],
},
{
id: 5,
name: '輔導室',
status: 1,
createTime: '2023/08/01 09:00:00',
note: '負責學生心理輔導與生涯規劃',
children: [],
},
])
function addChildById (items: DeptItem[], parentId: string | number, child: DeptItem): boolean {
for (const current of items) {
if (!current) continue
if (current.id === parentId) {
if (!current.children) current.children = []
current.children.push(child)
return true
}
if (current.children && current.children.length > 0) {
const found = addChildById(current.children, parentId, child)
if (found) return true
}
}
return false
}
function updateTreeItemById (items: DeptItem[], updated: DeptItem): boolean {
for (let i = 0; i < items.length; i += 1) {
const current = items[i]
if (!current) continue
if (current.id === updated.id) {
items[i] = {
...current,
name: updated.name,
note: updated.note,
status: updated.status,
}
return true
}
if (current.children && current.children.length > 0) {
const found = updateTreeItemById(current.children, updated)
if (found) return true
}
}
return false
}
const onCreate = () => alert('Create Dept')
function onAddSub (parent: DeptItem, newItem: DeptItem) {
addChildById(deptItems.value, parent.id, newItem)
}
function onEdit (item: DeptItem) {
updateTreeItemById(deptItems.value, item)
}
function onDelete (item: DeptItem) {
if (confirm(`Delete ${item.name}?`)) {
alert('Deleted')
}
}
</script>
+14
View File
@@ -0,0 +1,14 @@
<template>
<v-sheet height="100%" width="100%">
{{ fncId }}
</v-sheet>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const fncId = computed(() => String(route.params.fncId ?? ''))
</script>
+245
View File
@@ -0,0 +1,245 @@
<template>
<v-container class="pa-0" fluid>
<div class="d-flex flex-column ga-5 py-4 pr-2 pl-0">
<v-sheet class="d-flex flex-column flex-sm-row align-start align-sm-center ga-4 pa-5 elevation-1" color="surface">
<v-avatar color="primary" size="52" variant="tonal">
<span class="text-h5">👋</span>
</v-avatar>
<div>
<div class="text-h5 font-weight-bold">歡迎使用校務資訊系統</div>
<div class="text-body-2 text-medium-emphasis mt-1">
使用頂部搜尋框快速找到功能或從左側選單瀏覽所有系統模組
</div>
</div>
</v-sheet>
<section class="d-flex flex-column">
<div class="d-flex align-center ga-2 text-h6 font-weight-bold">📰 最新消息</div>
<!--
使用 v-data-iterator 讓消息列表具備一致的資料迭代結構
也方便未來需要加上排序 / 分頁時直接擴充
-->
<v-data-iterator class="mt-2" item-key="id" :items="newsItems" :items-per-page="-1">
<!--
v-data-iterator default slot 會提供包裝後的 items
這裡透過 resolveNewsItem 抽出原始資料再沿用原本的卡片排版
-->
<template #default="{ items }">
<v-row dense>
<v-col v-for="wrapped in items" :key="resolveNewsItem(wrapped).id" cols="12">
<v-card
class="news-item d-flex flex-column flex-sm-row ga-4 pa-4 bg-surface" variant="outlined"
@click="handleNews(resolveNewsItem(wrapped))">
<v-sheet class="news-badge">
<div class="news-badge-date">{{ resolveNewsItem(wrapped).date }}</div>
<div class="news-badge-month">{{ resolveNewsItem(wrapped).month }}</div>
</v-sheet>
<div class="flex-grow-1">
<div class="d-flex flex-wrap align-center font-weight-bold">
{{ resolveNewsItem(wrapped).title }}
<v-chip
v-if="resolveNewsItem(wrapped).isNew" class="ml-2" color="primary" size="x-small"
variant="flat">
NEW
</v-chip>
</div>
<div class="text-body-2 text-medium-emphasis mt-2">
{{ resolveNewsItem(wrapped).desc }}
</div>
<div class="d-flex ga-4 mt-3 text-caption text-medium-emphasis">
<div class="d-flex align-center ga-1">
<v-icon size="14">mdi-folder-outline</v-icon>
<span>{{ resolveNewsItem(wrapped).dept }}</span>
</div>
<div class="d-flex align-center ga-1">
<v-icon size="14">mdi-eye-outline</v-icon>
<span>{{ resolveNewsItem(wrapped).views }} 次瀏覽</span>
</div>
</div>
</div>
</v-card>
</v-col>
</v-row>
</template>
</v-data-iterator>
</section>
<v-card
class="d-flex align-center justify-space-between ga-3 px-5 py-4" color="secondary" rounded="xl"
variant="tonal" @click="handleMessageCenter">
<div class="d-flex align-center ga-4">
<v-avatar color="secondary" size="44" variant="flat">
<span class="text-h6"></span>
</v-avatar>
<div>
<div class="text-subtitle-1 font-weight-bold">訊息中心</div>
<div class="text-body-2 font-weight-bold text-on-secondary">12 筆未讀</div>
</div>
</div>
<div class="text-body-2 font-weight-medium">查看全部 </div>
</v-card>
<section class="d-flex flex-column pb-4">
<div class="d-flex align-center ga-2 text-h6 font-weight-bold">🚀 快速存取</div>
<v-row class="mt-2" dense>
<v-col v-for="item in quickItems" :key="item.title" cols="6" md="2" sm="4">
<v-card
class="d-flex flex-column align-center ga-2 text-center py-4 px-2 quick-item" variant="outlined"
@click="handleQuick(item)">
<div class="text-h5">{{ item.icon }}</div>
<div class="text-body-2 font-weight-medium">{{ item.title }}</div>
</v-card>
</v-col>
</v-row>
</section>
</div>
<!--
點擊消息後顯示的對話框
僅負責呈現內容不做任何延伸操作確保互動行為單純可預期
-->
<v-dialog v-model="isNewsDialogOpen" max-width="640">
<v-card v-if="selectedNews">
<v-card-title class="text-h6 font-weight-bold bg-primary-variant pa-4">
{{ selectedNews.title }}
</v-card-title>
<v-card-subtitle class="text-body-2 pt-4 text-medium-emphasis">
{{ selectedNews.month }} {{ selectedNews.date }} · {{ selectedNews.dept }} ·
{{ selectedNews.views }} 次瀏覽
</v-card-subtitle>
<v-card-text class="pt-4">
{{ selectedNews.desc }}
</v-card-text>
<v-card-actions class="justify-end">
<v-btn color="primary" variant="text" @click="isNewsDialogOpen = false">關閉</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-container>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useMessageStore } from '@/stores/messages'
import { useSnackbarStore } from '@/stores/snackbar'
const snackbar = useSnackbarStore()
const messageStore = useMessageStore()
const newsItems = [
{
id: 1,
date: '29',
month: '1月',
title: '113學年度第2學期加退選開始',
desc: '加退選時間為1月29日至2月9日止,請同學把握時間完成選課作業。',
dept: '教務處',
views: '1,234',
isNew: true,
},
{
id: 2,
date: '27',
month: '1月',
title: '場地借用系統維護通知',
desc: '系統將於本週六凌晨01:00-05:00進行維護,期間暫停服務。',
dept: '總務處',
views: '856',
isNew: false,
},
{
id: 3,
date: '25',
month: '1月',
title: '112學年度第1學期期末成績已開放查詢',
desc: '同學可至「查詢 > 教務資訊查詢 > 學期成績查詢」查看本學期成績。',
dept: '教務處',
views: '3,567',
isNew: false,
},
]
type NewsItem = (typeof newsItems)[number]
const quickItems = [
{ icon: '', title: '線上加選' },
{ icon: '', title: '線上退選' },
{ icon: '📊', title: '成績查詢' },
{ icon: '📅', title: '個人課表' },
{ icon: '📝', title: '網路請假' },
{ icon: '🏢', title: '場地借用' },
]
const selectedNews = ref<NewsItem | null>(null)
const isNewsDialogOpen = ref(false)
// v-data-iterator 會包裝 items,這個方法用來安全地取回原始資料結構。
function resolveNewsItem (wrapped: unknown): NewsItem {
if (wrapped && typeof wrapped === 'object' && 'raw' in wrapped) {
return (wrapped as { raw: NewsItem }).raw
}
return wrapped as NewsItem
}
function handleNews (item: NewsItem) {
selectedNews.value = item
isNewsDialogOpen.value = true
}
// 點擊首頁「訊息中心」卡片,開啟共用的訊息清單 dialog
function handleMessageCenter () {
messageStore.open()
}
function handleQuick (item: (typeof quickItems)[number]) {
snackbar.show({ message: `前往:${item.title}`, color: 'info' })
}
</script>
<style scoped>
.news-item {
cursor: pointer;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.news-item:hover {
transform: translateY(-2px);
box-shadow: 0 10px 24px rgba(var(--v-theme-on-surface), 0.12);
}
.news-badge {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: rgb(var(--v-theme-primary));
color: rgb(var(--v-theme-on-primary));
border-radius: 12px;
padding: 10px 6px;
min-height: 64px;
min-width: 64px;
}
.news-badge-date {
font-size: 20px;
font-weight: 700;
line-height: 1;
}
.news-badge-month {
font-size: 12px;
margin-top: 4px;
}
.quick-item {
display: flex;
cursor: pointer;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.quick-item:hover {
transform: translateY(-2px);
box-shadow: 0 10px 24px rgba(var(--v-theme-on-surface), 0.12);
}
</style>
+259
View File
@@ -0,0 +1,259 @@
<template>
<SKLogin
:announcement-board="announcementBoard"
:branding="branding"
:form="form"
:header="header"
:illustration="illustration"
:layout="formPositionLayout" :mobile-announcement="mobileAnnouncement" :toolbar="toolbar"
@captcha-change="handleCaptchaChange" @captcha-refresh="handleCaptchaRefresh" @change-locale="handleChangeLocale"
@forgot-password="handleForgotPassword" @select-announcement="handleSelectAnnouncement" @submit="onLogin"
@toggle-layout="handleToggleLayout" />
<v-dialog v-model="dialogVisible" width="360">
<v-card>
<v-card-title>{{ dialogTitle }}</v-card-title>
<v-card-text>{{ dialogMessage }}</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn color="primary" variant="flat" @click="dialogVisible = false">
{{ t('common.ok') }}
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog v-model="announcementDialogVisible" max-width="720">
<v-card>
<v-card-title class="text-h6">
{{ selectedAnnouncement?.title }}
</v-card-title>
<v-card-subtitle class="pt-2">
{{ selectedAnnouncement?.date }} {{ selectedAnnouncement?.school }}
</v-card-subtitle>
<v-card-text class="text-body-1">
{{ selectedAnnouncementDetail }}
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn color="primary" variant="flat" @click="announcementDialogVisible = false">
關閉
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</template>
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import HyakkaouAcademyImage from '@/assets/logo.png'
import SKLogin from '@/components/SKLogin.vue'
import { useAuthStore } from '@/stores/auth'
import { type LoginAnnouncementListItem, useLoginAnnouncementsStore } from '@/stores/loginAnnouncements'
import { useMenuStore } from '@/stores/menu'
import { useSnackbarStore } from '@/stores/snackbar'
type LayoutType = 'side-left' | 'side-right' | 'card'
// i18n
const { t, locale } = useI18n()
const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const loginAnnouncementsStore = useLoginAnnouncementsStore()
const menuStore = useMenuStore()
const snackbarStore = useSnackbarStore()
const {
boardConfig: announcementBoard,
mobileAnnouncementConfig: mobileAnnouncement,
selectedAnnouncement,
selectedAnnouncementDetail,
} =
storeToRefs(loginAnnouncementsStore)
// 語系選項
const locales = ['zh-TW', 'en-US']
// 插圖圖片來源
const illustrationImage = ref(HyakkaouAcademyImage)
// 功能開關與版型
const formPositionLayout = ref<LayoutType>('side-left')
// 功能開關:是否啟用驗證碼
const withCaptcha = ref(true)
// 文字內容(i18n
const title = computed(() => t('pages.login.title'))
const organization = computed(() => t('pages.login.organization'))
const accPlaceholder = computed(() => t('pages.login.accPlaceholder'))
const passwPlaceholder = computed(() => t('pages.login.passwPlaceholder'))
const illustrationTitle = computed(() => t('pages.login.illustrationTitle'))
const illustrationDescription = computed(() => t('pages.login.illustrationDescription'))
const welcomeText = computed(() => t('pages.login.welcomeText'))
const welcomeDescription = computed(() => t('pages.login.welcomeDescription'))
const rememberMeLabel = computed(() => t('pages.login.rememberMeLabel'))
const forgotPasswordText = computed(() => t('pages.login.forgotPasswordText'))
const submitText = computed(() => t('pages.login.submitText'))
const verifyText = computed(() => t('pages.login.verifyText'))
const captchaPlaceholder = computed(() => t('pages.login.captchaPlaceholder'))
const refreshTitle = computed(() => t('pages.login.refreshTitle'))
// 連結與儲存設定
// 忘記密碼連結(由 form.forgotPassword 設定)
const forgotPasswordHref = ref('/forgot-password')
const forgotPasswordTarget = ref<string | undefined>(undefined)
// 記住帳號的 localStorage key
const rememberStorageKey = ref('playground.login.remember.username')
// 驗證碼 API
const captchaValue = ref('')
// 驗證與對話框狀態
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogMessage = ref('')
const announcementDialogVisible = ref(false)
// 內容組合(傳入 SKLogin
const branding = computed(() => ({
title: title.value,
organization: organization.value,
}))
const illustration = computed(() => ({
image: illustrationImage.value,
title: illustrationTitle.value,
description: illustrationDescription.value,
}))
const header = computed(() => ({
welcomeText: welcomeText.value,
welcomeDescription: welcomeDescription.value,
}))
// 表單區塊設定(含功能開關)
const form = computed(() => ({
accPlaceholder: accPlaceholder.value,
passwPlaceholder: passwPlaceholder.value,
rememberMeLabel: rememberMeLabel.value,
submitText: submitText.value,
verifyText: verifyText.value,
captchaPlaceholder: captchaPlaceholder.value,
refreshTitle: refreshTitle.value,
rememberStorageKey: rememberStorageKey.value,
// 功能開關:是否顯示驗證碼
withCaptcha: withCaptcha.value,
captcha: authStore.captcha
? {
imgUrl: authStore.captcha.dntCaptchaImgUrl,
id: authStore.captcha.dntCaptchaId,
tokenValue: authStore.captcha.dntCaptchaTokenValue,
}
: undefined,
captchaValue: captchaValue.value,
captchaLoading: authStore.captchaLoading,
captchaErrorMessage: authStore.captchaErrorMessage ?? '',
captchaVerified: false,
forgotPassword: {
text: forgotPasswordText.value,
href: forgotPasswordHref.value,
target: forgotPasswordTarget.value,
},
}))
// 右上工具列設定(含顯示開關)
const toolbar = computed(() => ({
// 功能開關:是否顯示語系切換工具列
show: true,
locale: locale.value,
locales,
}))
// 事件處理
function handleForgotPassword (e: MouseEvent) {
console.log('Playground Forgot Password Click:', e)
}
function handleChangeLocale (nextLocale: string) {
locale.value = nextLocale
localStorage.setItem('playground.locale', nextLocale)
}
async function handleCaptchaRefresh () {
captchaValue.value = ''
await authStore.getCaptcha()
}
function handleCaptchaChange (value: string) {
captchaValue.value = value
}
function handleToggleLayout () {
const layoutOrder: LayoutType[] = ['side-left', 'side-right', 'card']
const currentIndex = layoutOrder.indexOf(formPositionLayout.value)
const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % layoutOrder.length
formPositionLayout.value = layoutOrder[nextIndex] ?? 'side-left'
}
function handleSelectAnnouncement (item: LoginAnnouncementListItem) {
loginAnnouncementsStore.selectById(item.id)
announcementDialogVisible.value = true
}
async function onLogin (data: Record<string, unknown>) {
if (withCaptcha.value && !captchaValue.value) {
dialogTitle.value = t('common.notice')
dialogMessage.value = t('pages.login.alert.verifyRequired')
dialogVisible.value = true
return
}
try {
dialogTitle.value = t('common.notice')
const inputUserId = String(data.username ?? '').trim()
const inputPassword = String(data.password ?? '').trim()
const isDev = import.meta.env.DEV
const devDefaultUserId = String(import.meta.env.VITE_DEV_DEFAULT_USER_ID ?? '').trim()
const devDefaultPassword = String(import.meta.env.VITE_DEV_DEFAULT_PASSWORD ?? '').trim()
const userId = isDev && !inputUserId ? devDefaultUserId : inputUserId
const password = isDev && !inputPassword ? devDefaultPassword : inputPassword
await authStore.login({
UserID: userId,
Password: password,
DNTCaptchaInputText: captchaValue.value,
})
menuStore.getMenu(authStore.user?.id ?? '')
// menuStore.getFavorite(authStore.user?.id ?? '')
snackbarStore.show({
message: t('pages.login.alert.loginSuccess'),
color: 'success',
timeout: 2000,
location: 'top right',
variant: 'flat',
})
const redirect = (route.query.redirect as string) || '/'
await router.push(redirect.startsWith('/') ? redirect : '/')
} catch (error) {
console.error('Login error:', error)
dialogTitle.value = t('common.notice')
dialogMessage.value = t('pages.login.alert.loginFailed')
dialogVisible.value = true
}
}
onMounted(() => {
loginAnnouncementsStore.hydrate()
loginAnnouncementsStore.fetchMobileAnnouncements()
authStore.getCaptcha()
})
</script>
+144
View File
@@ -0,0 +1,144 @@
<template>
<SKMenuManagement
:items="menuItems"
:loading="loading"
:permission-options="permissionOptions"
:status-options="statusOptions"
@edit="onEdit"
/>
</template>
<script setup lang="ts">
import type { MenuItem } from '@/components/SKMenuManagement.vue'
import { ref } from 'vue'
import SKMenuManagement from '@/components/SKMenuManagement.vue'
const loading = ref(false)
const statusOptions = [
{ title: '已啟用', value: 1 },
{ title: '已禁用', value: 0 },
]
const permissionOptions = ['管理員', '一級主管', '二級主管', '使用者']
const menuItems = ref([
{
id: 1,
title: '工作台',
permission: '使用者',
path: '/workspace',
component: '/dashboard/workspace/index',
status: 1,
children: [],
},
{
id: 2,
title: '系統管理',
permission: '管理員',
path: '/system',
component: 'LAYOUT',
status: 1,
isNew: true,
children: [
{
id: 21,
title: '菜單管理',
permission: '管理員',
path: '/system/menu',
component: '/system/menu/list',
status: 1,
children: [
{
id: 211,
title: '新增',
permission: '管理員',
status: 1,
},
{
id: 212,
title: '修改',
permission: '管理員',
status: 1,
},
{
id: 213,
title: '刪除',
permission: '管理員',
status: 1,
},
],
},
{
id: 22,
title: '部門管理',
permission: '一級主管',
path: '/system/dept',
component: '/system/dept/list',
status: 1,
children: [],
},
],
},
{
id: 3,
title: '項目',
permission: '二級主管',
path: '/vben-admin',
component: 'LAYOUT',
status: 1,
children: [
{
id: 31,
title: '文檔',
permission: '使用者',
path: '/vben-admin/document',
component: 'https://doc.vben.pro',
status: 1,
},
{
id: 32,
title: 'Ant Design Vue 版本',
permission: '使用者',
path: '/vben-admin/antdv',
component: 'https://ant.vben.pro',
status: 0,
},
],
},
{
id: 4,
title: '關於',
permission: '使用者',
path: '/about',
component: '_core/about/index',
status: 1,
children: [],
},
])
function updateTreeItemById (items: MenuItem[], updated: MenuItem): boolean {
for (let i = 0; i < items.length; i += 1) {
const current = items[i]
if (!current) continue
if (current.id === updated.id) {
items[i] = {
...current,
status: updated.status,
permission: updated.permission,
}
return true
}
if (current.children && current.children.length > 0) {
const found = updateTreeItemById(current.children, updated)
if (found) return true
}
}
return false
}
function onEdit (item: MenuItem) {
updateTreeItemById(menuItems.value, item)
}
</script>
+122
View File
@@ -0,0 +1,122 @@
<template>
<SKRoleManagement
:loading="loading"
:roles="roles"
@create="onCreate"
@delete="onDelete"
@edit="onEdit"
@reset="onReset"
@search="onSearch"
@update:status="onStatusUpdate"
/>
</template>
<script setup lang="ts">
import type { RoleItem } from '@/components/SKRoleManagement.vue'
import { ref } from 'vue'
import SKRoleManagement from '@/components/SKRoleManagement.vue'
const loading = ref(false)
const roles = ref([
{
name: 'Car',
id: '2216c0ab-9d0e-4f6e-a7d6-12...',
status: false,
note: 'Somnus careo ultio caste vix adversus textilis vaco defero coniuratio.',
createTime: '2022/05/13 01:03:31',
},
{
name: 'Chair',
id: '2625810b-639f-4213-944e-ae...',
status: false,
note: 'Ulterius tristis voluptatum demergo.',
createTime: '2024/05/30 21:04:49',
},
{
name: 'Shoes',
id: 'c19c2b27-f9c9-46b8-93db-11f...',
status: true,
note: 'Illum delinquo texo tumultus perferendis debilito.',
createTime: '2024/07/18 06:21:55',
},
{
name: 'Cheese',
id: '7d1053ac-acc1-405f-8c66-235...',
status: true,
note: 'Acidus vobis coruscus.',
createTime: '2024/07/03 07:44:10',
},
{
name: 'Gloves',
id: '9bb9ed44-dfcd-11b8-bcb1-d0...',
status: true,
note: 'Vivo caelum quo caveo valetudo.',
createTime: '2024/10/05 12:00:17',
},
{
name: 'Shoes',
id: 'cdb0c47a-284e-4ca3-b434-e8...',
status: true,
note: 'Veritas adflicto temperantia.',
createTime: '2024/11/20 16:35:09',
},
{
name: 'Computer',
id: 'db9d1509-7247-4a38-9bd9-b...',
status: true,
note: 'Viridis titulus somnus voluptate voluptate aspicio sophismata ansor th...',
createTime: '2023/02/21 06:16:25',
},
{
name: 'Cheese',
id: '1beb5ce6-11f2-490f-9549-101...',
status: true,
note: 'Eveniet amicitia bestia supra.',
createTime: '2022/02/19 12:51:41',
},
{
name: 'Towels',
id: 'bd9c74bb-fc3a-4a7a-8b3f-55f...',
status: true,
note: 'Dapifer aliquam amoveo vitium ubi repellendus tactus bardus crepusc...',
createTime: '2023/02/16 20:09:27',
},
])
function onSearch (params: Record<string, unknown>) {
console.log('Search:', params)
loading.value = true
setTimeout(() => {
loading.value = false
alert('Search Triggered! Check Console.')
}, 500)
}
function onReset () {
console.log('Reset')
}
function onCreate () {
console.log('Create Role')
alert('Create Role Clicked')
}
function onEdit (item: RoleItem) {
console.log('Edit:', item)
alert(`Edit ${item.name}`)
}
function onDelete (item: RoleItem) {
console.log('Delete:', item)
if (confirm(`Are you sure you want to delete ${item.name}?`)) {
roles.value = roles.value.filter((r) => r.id !== item.id)
}
}
function onStatusUpdate (item: RoleItem, newVal: boolean) {
// In a real app, API call here
item.status = newVal
console.log('Status Update:', item.name, newVal)
}
</script>
+5
View File
@@ -0,0 +1,5 @@
<template>
<div>設定頁面</div>
</template>
<script setup lang="ts"></script>
+110
View File
@@ -0,0 +1,110 @@
<template>
<v-container class="fill-height">
<v-row align="center" justify="center" no-gutters>
<v-col cols="12" md="8" sm="10">
<v-card border class="pa-6" variant="flat">
<v-card-title class="d-flex align-center ga-3">
<v-icon :color="color" size="36">{{ icon }}</v-icon>
<div class="text-h5">{{ title }}</div>
<div class="text-caption text-medium-emphasis">{{ codeLabel }}</div>
<v-spacer />
<img alt="robot" class="robot-icon" height="32" src="@/assets/robot-svgrepo-com.svg" width="32" />
</v-card-title>
<v-card-text v-if="description" class="text-body-1 mt-4">
<p class="py-3">
{{ description }}
</p>
<v-alert v-if="backendMessage" class="mt-6" :color="color" density="compact" type="warning" variant="tonal">
{{ backendMessage }}
</v-alert>
</v-card-text>
<v-card-actions class="mt-6">
<v-btn v-if="showBack" variant="text" @click="router.back()">返回上一頁</v-btn>
<v-spacer />
<v-btn v-if="showHome" color="primary" :to="{ name: 'home' }" variant="flat">回到首頁</v-btn>
<v-btn v-if="showLogin" class="ml-2" color="primary" :to="{ name: 'login' }" variant="outlined">
前往登入
</v-btn>
</v-card-actions>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
type Props = {
code: string | number
title: string
description?: string
icon?: string
color?: string
showHome?: boolean
showLogin?: boolean
showBack?: boolean
}
const props = withDefaults(defineProps<Props>(), {
description: undefined,
icon: 'mdi-alert-circle-outline',
color: 'warning',
showHome: true,
showLogin: true,
showBack: true
})
const route = useRoute()
const router = useRouter()
const codeLabel = computed(() => {
const code = props.code
return typeof code === 'number' ? `HTTP ${code}` : String(code)
})
const backendMessage = computed(() => {
const raw = route.query.message
if (typeof raw !== 'string') return ''
return raw.trim()
})
</script>
<style scoped>
@keyframes breathe {
0%, 100% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.05);
opacity: 0.8;
}
}
@keyframes blink {
0%, 45%, 55%, 100% {
opacity: 1;
}
50% {
opacity: 0.3;
}
}
.robot-icon {
animation: breathe 3s ease-in-out infinite;
}
.robot-icon path:nth-child(2),
.robot-icon path:nth-child(3) {
animation: blink 4s ease-in-out infinite;
}
.robot-icon path:nth-child(3) {
animation-delay: 0.1s;
}
</style>
+13
View File
@@ -0,0 +1,13 @@
<template>
<ErrorShell
:code="403"
color="warning"
description="你沒有權限存取此頁面或操作。"
icon="mdi-shield-lock-outline"
title="沒有權限"
/>
</template>
<script setup lang="ts">
import ErrorShell from './ErrorShell.vue'
</script>
+15
View File
@@ -0,0 +1,15 @@
<template>
<ErrorShell
code="MAINTENANCE"
color="info"
description="目前系統正在維護,請稍後再試。"
icon="mdi-tools"
:show-login="false"
title="系統維護中"
/>
</template>
<script setup lang="ts">
import ErrorShell from './ErrorShell.vue'
</script>
+14
View File
@@ -0,0 +1,14 @@
<template>
<ErrorShell
code="NETWORK"
color="warning"
description="無法連線到伺服器,請檢查網路或稍後再試。"
icon="mdi-wifi-off"
title="網路連線異常"
/>
</template>
<script setup lang="ts">
import ErrorShell from './ErrorShell.vue'
</script>
+14
View File
@@ -0,0 +1,14 @@
<template>
<ErrorShell
:code="404"
color="info"
description="你輸入的網址不存在,或頁面已被移除。"
icon="mdi-map-marker-question-outline"
:show-login="false"
title="找不到頁面"
/>
</template>
<script setup lang="ts">
import ErrorShell from './ErrorShell.vue'
</script>
+14
View File
@@ -0,0 +1,14 @@
<template>
<ErrorShell
:code="500"
color="error"
description="伺服器發生非預期錯誤,請稍後再試。"
icon="mdi-server"
title="系統發生錯誤"
/>
</template>
<script setup lang="ts">
import ErrorShell from './ErrorShell.vue'
</script>
+14
View File
@@ -0,0 +1,14 @@
<template>
<ErrorShell
:code="503"
color="warning"
description="服務目前無法使用,請稍後再試。"
icon="mdi-server-off"
title="服務暫時無法使用"
/>
</template>
<script setup lang="ts">
import ErrorShell from './ErrorShell.vue'
</script>
+392
View File
@@ -0,0 +1,392 @@
<template>
<div class="d-flex flex-column">
<v-card variant="flat">
<v-card-title class="d-flex flex-wrap align-center py-0 ga-2">
<span class="text-h6">可編輯表格維護示範</span>
<v-chip :color="hasAnyChange ? 'warning' : 'success'" variant="tonal">
{{ hasAnyChange ? '有未儲存變更' : '已同步' }}
</v-chip>
<v-chip color="info" variant="tonal">筆數 {{ filteredStudents.length }}</v-chip>
<v-spacer />
<v-btn flat prepend-icon="mdi-magnify" @click="isSearchVisible = !isSearchVisible">條件搜尋</v-btn>
<v-switch v-model="isBulkEditEnabled" color="primary" hide-details label="啟用編輯" />
</v-card-title>
<v-divider />
<v-card-text class="pb-0 pt-2">
<!-- 搜尋條件 -->
<v-row v-if="isSearchVisible" class="mb-2" dense>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">學號</div>
<v-text-field
v-model="search.studentId" clearable density="compact" hide-details
placeholder="例如:S2024001" variant="outlined" />
</v-col>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">姓名</div>
<v-text-field
v-model="search.name" clearable density="compact" hide-details placeholder="例如:王小明"
variant="outlined" />
</v-col>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">系所</div>
<v-select
v-model="search.department" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" clearable density="compact" hide-details
:items="departments" variant="outlined" />
</v-col>
</v-row>
<!-- 操作 -->
<v-row v-if="isBulkEditEnabled" align="center" class="mb-2 ga-1" dense>
<v-btn :disabled="!hasSelectedRows" prepend-icon="mdi-delete" variant="outlined" @click="deleteSelectedRows">
批次刪除
</v-btn>
<v-spacer></v-spacer>
<v-btn
color="primary" :disabled="!hasAnyChange" prepend-icon="mdi-content-save" variant="outlined"
@click="saveAllRows">
儲存變更
</v-btn>
<v-btn :disabled="!hasAnyChange" prepend-icon="mdi-restore" variant="text" @click="resetAllRows">
取消變更
</v-btn>
</v-row>
<div ref="tableContainerRef">
<v-data-table
density="comfortable" fixed-header :headers="tableHeaders" :height="tableHeight"
item-value="id" :items="filteredStudents" :items-per-page="10" items-per-page-text="每頁筆數"
page-text=" {0}-{1} / {2} ">
<template #[`header.select`]>
<v-checkbox-btn
:disabled="!isBulkEditEnabled" :indeterminate="isPartiallyVisibleSelected"
:model-value="isAllVisibleSelected" @update:model-value="toggleSelectAll" />
</template>
<template #[`item.select`]="{ item }">
<v-checkbox-btn
:disabled="!isBulkEditEnabled" :model-value="selectedRowIds.includes(item.id)"
@update:model-value="(checked) => toggleSingleRowSelection(item.id, checked)" />
</template>
<template #[`item.studentId`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.studentId" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.name`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.name" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.department`]="{ item }">
<v-select
v-model="draftRows[item.id]!.department" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details :items="departments" :readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.grade`]="{ item }">
<v-select
v-model="draftRows[item.id]!.grade" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details item-title="title" item-value="value" :items="gradeOptions"
:readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.enrollYear`]="{ item }">
<v-select
v-model="draftRows[item.id]!.enrollYear" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details :items="enrollYears" :readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.credits`]="{ item }">
<v-text-field
v-model.number="draftRows[item.id]!.credits" density="compact" flat hide-details min="0"
:readonly="!isBulkEditEnabled" type="number" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.advisor`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.advisor" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.email`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.email" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.phone`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.phone" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.status`]="{ item }">
<v-select
v-model="draftRows[item.id]!.status" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details :items="statuses" :readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.actions`]="{ item }">
<div class="d-flex ga-1 justify-end">
<v-btn
color="error" :disabled="!isBulkEditEnabled" size="small" variant="text"
@click="deleteSingleRow(item.id)">
刪除
</v-btn>
</div>
</template>
</v-data-table>
</div>
</v-card-text>
</v-card>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { type StudentRecord, useStudentStore } from '@/stores/students'
type StudentPayload = Omit<StudentRecord, 'id'>
const studentStore = useStudentStore()
const students = computed(() => studentStore.students)
const departments = ['資訊工程', '企業管理', '應用外語', '視覺設計', '財務金融']
const gradeOptions = [
{ title: '大一', value: 1 },
{ title: '大二', value: 2 },
{ title: '大三', value: 3 },
{ title: '大四', value: 4 },
{ title: '研究所', value: 5 },
]
const enrollYears = [2024, 2023, 2022, 2021, 2020, 2019]
const statuses = ['在學', '休學', '畢業']
const tableHeaders = [
{ title: '', key: 'select', sortable: false, nowrap: true },
{ title: '學號', key: 'studentId', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '姓名', key: 'name', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '系所', key: 'department', sortable: true, minWidth: 140, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '年級', key: 'grade', sortable: true, minWidth: 140, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '入學年度', key: 'enrollYear', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '已修學分', key: 'credits', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '指導老師', key: 'advisor', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: 'Email', key: 'email', sortable: true, minWidth: 200, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '電話', key: 'phone', sortable: true, minWidth: 150, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '狀態', key: 'status', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '操作', key: 'actions', sortable: false, width: 'auto', nowrap: true, cellProps: { class: 'bg-background' } },
] as const
const search = ref({
studentId: '',
name: '',
department: '',
})
const isBulkEditEnabled = ref(false)
const isSearchVisible = ref(false)
const tableContainerRef = ref<HTMLElement | null>(null)
const tableScrollParentRef = ref<HTMLElement | null>(null)
const tableResizeObserver = ref<ResizeObserver | null>(null)
const tableHeight = ref(300)
const draftRows = ref<Record<number, StudentPayload>>({})
const selectedRowIds = ref<number[]>([])
const TABLE_BOTTOM_GAP = 64
const TABLE_MIN_HEIGHT = 240
function toPayload (student: StudentRecord): StudentPayload {
return {
studentId: student.studentId,
name: student.name,
department: student.department,
grade: student.grade,
enrollYear: student.enrollYear,
credits: student.credits,
advisor: student.advisor,
email: student.email,
phone: student.phone,
status: student.status,
}
}
function rebuildDraftRows () {
draftRows.value = Object.fromEntries(students.value.map((item) => [item.id, toPayload(item)]))
}
const getSourceRow = (id: number) => students.value.find((item) => item.id === id) || null
function isRowDirty (id: number) {
const source = getSourceRow(id)
const draft = draftRows.value[id]
if (!source || !draft) return false
return (
source.studentId !== draft.studentId ||
source.name !== draft.name ||
source.department !== draft.department ||
source.grade !== draft.grade ||
source.enrollYear !== draft.enrollYear ||
source.credits !== draft.credits ||
source.advisor !== draft.advisor ||
source.email !== draft.email ||
source.phone !== draft.phone ||
source.status !== draft.status
)
}
const filteredStudents = computed(() => {
const keywordStudentId = search.value.studentId.trim().toLowerCase()
const keywordName = search.value.name.trim().toLowerCase()
const selectedDepartment = search.value.department
return students.value.filter((item) => {
if (studentStore.isMarkedAsDeleted(item.id)) return false
const matchesStudentId = keywordStudentId
? item.studentId.toLowerCase().includes(keywordStudentId)
: true
const matchesName = keywordName ? item.name.toLowerCase().includes(keywordName) : true
const matchesDepartment = selectedDepartment ? item.department === selectedDepartment : true
return matchesStudentId && matchesName && matchesDepartment
})
})
const visibleStudentIds = computed(() => filteredStudents.value.map((item) => item.id))
const isAllVisibleSelected = computed(() =>
visibleStudentIds.value.length > 0 && visibleStudentIds.value.every((id) => selectedRowIds.value.includes(id))
)
const isPartiallyVisibleSelected = computed(() =>
visibleStudentIds.value.some((id) => selectedRowIds.value.includes(id)) && !isAllVisibleSelected.value
)
function toggleSelectAll (checked: boolean | null) {
if (isPartiallyVisibleSelected.value) {
selectedRowIds.value = selectedRowIds.value.filter((id) => !visibleStudentIds.value.includes(id))
return
}
if (!checked) {
selectedRowIds.value = selectedRowIds.value.filter((id) => !visibleStudentIds.value.includes(id))
return
}
selectedRowIds.value = Array.from(new Set([...selectedRowIds.value, ...visibleStudentIds.value]))
}
function toggleSingleRowSelection (id: number, checked: boolean | null) {
if (checked) {
if (!selectedRowIds.value.includes(id)) {
selectedRowIds.value = [...selectedRowIds.value, id]
}
return
}
selectedRowIds.value = selectedRowIds.value.filter((selectedId) => selectedId !== id)
}
const hasAnyChange = computed(() =>
students.value.some((item) => isRowDirty(item.id)) || studentStore.deletedIds.size > 0
)
const hasSelectedRows = computed(() => selectedRowIds.value.length > 0)
function deleteSingleRow (id: number) {
selectedRowIds.value = selectedRowIds.value.filter((selectedId) => selectedId !== id)
studentStore.markAsDeleted(id)
rebuildDraftRows()
}
function deleteSelectedRows () {
if (selectedRowIds.value.length === 0) return
for (const id of selectedRowIds.value) {
studentStore.markAsDeleted(id)
}
selectedRowIds.value = []
rebuildDraftRows()
}
function saveAllRows () {
for (const item of students.value) {
const draft = draftRows.value[item.id]
if (!draft) continue
if (!isRowDirty(item.id)) continue
studentStore.updateStudent(item.id, draft)
}
studentStore.commitDeleted()
rebuildDraftRows()
}
function resetAllRows () {
studentStore.restoreDeleted()
selectedRowIds.value = []
rebuildDraftRows()
}
function recalculateTableHeight () {
const container = tableContainerRef.value
if (!container) return
const scrollParent = tableScrollParentRef.value || (container.closest('.overflow-auto') as HTMLElement | null)
tableScrollParentRef.value = scrollParent
const parentBottom = scrollParent
? scrollParent.getBoundingClientRect().bottom
: window.innerHeight
const top = container.getBoundingClientRect().top
const availableHeight = parentBottom - top - TABLE_BOTTOM_GAP
tableHeight.value = Math.max(TABLE_MIN_HEIGHT, Math.floor(availableHeight))
}
watch(students, () => {
const currentIds = new Set(students.value.map((item) => item.id))
selectedRowIds.value = selectedRowIds.value.filter((id) => currentIds.has(id))
})
watch(students, rebuildDraftRows, { immediate: true })
watch([isSearchVisible, isBulkEditEnabled], async () => {
await nextTick()
requestAnimationFrame(() => {
recalculateTableHeight()
})
})
onMounted(() => {
const container = tableContainerRef.value
if (container) {
tableScrollParentRef.value = container.closest('.overflow-auto') as HTMLElement | null
tableResizeObserver.value = new ResizeObserver(() => {
recalculateTableHeight()
})
tableResizeObserver.value.observe(container)
if (tableScrollParentRef.value) {
tableResizeObserver.value.observe(tableScrollParentRef.value)
}
}
requestAnimationFrame(() => {
recalculateTableHeight()
})
window.addEventListener('resize', recalculateTableHeight)
})
onBeforeUnmount(() => {
tableResizeObserver.value?.disconnect()
window.removeEventListener('resize', recalculateTableHeight)
})
</script>
<style scoped>
:deep(.select-hide-arrow .v-field__append-inner) {
display: none;
}
:deep(.v-table__wrapper .v-field__input) {
padding-top: 0 !important;
padding-bottom: 0 !important;
min-height: 32px;
}
:deep(.v-data-table-footer) {
padding: 4px 0 0;
}
</style>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+886
View File
@@ -0,0 +1,886 @@
<template>
<mnt-page-cards
:search-panel-open="searchPanelOpen" :title="`單筆資料維護示範`"
@create="openAddDialog" @toggle-search="searchPanelOpen = !searchPanelOpen">
<template #search-fields>
<v-col cols="12" md="2">
<div class="text-body-2 text-medium-emphasis pl-2">學號</div>
<v-text-field
v-model="search.studentId" density="compact" hide-details placeholder="例如:S2024001"
variant="outlined" />
</v-col>
<v-col cols="12" md="2">
<div class="text-body-2 text-medium-emphasis pl-2">姓名</div>
<v-text-field v-model="search.name" density="compact" hide-details placeholder="例如:王小明" variant="outlined" />
</v-col>
<v-col cols="12" md="2">
<div class="text-body-2 text-medium-emphasis pl-2">系所</div>
<v-select v-model="search.department" density="compact" hide-details :items="departments" variant="outlined" />
</v-col>
<v-col cols="12" md="2">
<div class="text-body-2 text-medium-emphasis pl-2">年級</div>
<v-select
v-model="search.grade" density="compact" hide-details item-title="title" item-value="value"
:items="gradeOptions" variant="outlined" />
</v-col>
<v-col cols="12" md="2">
<div class="text-body-2 text-medium-emphasis pl-2">狀態</div>
<v-select v-model="search.status" density="compact" hide-details :items="statuses" variant="outlined" />
</v-col>
<v-col class="d-flex justify-end align-end flex-grow-1 ga-2" cols="12" md="auto">
<v-btn prepend-icon="mdi-broom" variant="text" @click="resetSearch">清除</v-btn>
<v-btn color="primary" disabled prepend-icon="mdi-magnify" variant="tonal">查詢</v-btn>
</v-col>
</template>
<template #table>
<v-data-table
class="student-table" density="compact" fixed-header :headers="tableHeaders"
height="100%" :items="students" :items-per-page="10" items-per-page-text="每頁筆數" page-text=" {0}-{1} / {2} "
:row-props="rowProps">
<template #[`item.grade`]="{ item }">
{{ gradeLabel(item.grade) }}
</template>
<template #[`item.status`]="{ item }">
<v-chip :color="statusColor(item.status)" size="small" variant="tonal">
{{ item.status }}
</v-chip>
</template>
<template #[`item.actions`]="{ item }">
<div class="d-flex ga-2">
<v-btn color="info" prepend-icon="mdi-eye" size="small" variant="text" @click="openViewDialog(item)">
檢視
</v-btn>
<v-btn color="primary" prepend-icon="mdi-pencil" size="small" variant="text" @click="openEditDialog(item)">
修改
</v-btn>
<v-btn
color="error" prepend-icon="mdi-delete" size="small" variant="text"
@click="requestDeleteConfirmation(item)">
刪除
</v-btn>
</div>
</template>
</v-data-table>
</template>
</mnt-page-cards>
<!-- 新增 / 編輯 / 檢視側邊欄 -->
<teleport to="body">
<!-- 包成元件需要傳高度寬度給dialog-panel -->
<v-overlay
class="dialog-overlay" :close-on-content-click="false" :model-value="dialogVisible" scrim="rgba(0, 0, 0, 0.45)"
scroll-strategy="block" @update:model-value="handleDialogVisibility">
<div class="dialog-panel">
<mnt-dialog-card
content-class="pa-2 flex-grow-1 overflow-y-auto" :dialog-subtitle="dialogSubtitle" :dialog-title="dialogTitle"
:is-edit-mode="isEditMode" :is-view-mode="isViewMode" width="100%">
<template #toolbar>
<mnt-record-nav-toolbar
edit-label="進入編輯" first-label="第一筆"
:has-next-record="hasNextRecord" :has-prev-record="hasPrevRecord" :is-edit-mode="isEditMode" :is-view-mode="isViewMode"
last-label="最後一筆" view-label="回到檢視" @first="openEdgeRecord('first')" @last="openEdgeRecord('last')"
@next="openAdjacentRecord('next')" @prev="openAdjacentRecord('prev')" @switch-to-edit="switchToEditMode"
@switch-to-view="switchToViewMode" />
</template>
<template #content>
<!-- 儲存前驗證錯誤摘要 -->
<v-alert v-if="errorSummary.length > 0 && !isLoading" class="mb-4" type="error" variant="tonal">
<div class="text-subtitle-2 mb-2">請先修正以下問題</div>
<div class="d-flex flex-column ga-1">
<v-btn
v-for="error in errorSummary" :key="error.field" color="error" size="small" variant="text"
@click="scrollToField(error.field)">
{{ error.message }}
</v-btn>
</div>
</v-alert>
<!-- 編輯/檢視載入中骨架 -->
<v-skeleton-loader v-if="isLoading" class="mt-4" type="subtitle,paragraph" width="100%" />
<!-- 表單檢視模式使用 readonly避免 focus 狀態 -->
<v-form v-else :class="{ 'form-readonly': isFormReadonly }" @submit.prevent="requestSaveConfirmation">
<v-row dense>
<v-col cols="12" md="6">
<v-text-field
id="field-studentId" v-model="form.studentId" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.studentId" label="學號" placeholder="例如:S2024008"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('studentId')" />
</v-col>
<v-col cols="12" md="6">
<v-text-field
id="field-name" v-model="form.name" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.name"
label="姓名" placeholder="例如:陳怡君" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('name')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-department" v-model="form.department" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.department" :items="departments" label="系所"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('department')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-grade" v-model="form.grade" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.grade"
item-title="title" item-value="value" :items="gradeOptions" label="年級"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('grade')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-enrollYear" v-model="form.enrollYear" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.enrollYear" :items="enrollYears" label="入學年度"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('enrollYear')" />
</v-col>
<v-col cols="12" md="6">
<v-text-field
id="field-credits" v-model.number="form.credits" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.credits"
label="已修學分" min="0" :readonly="isFormReadonly"
type="number" variant="outlined"
@update:model-value="clearFieldError('credits')" />
</v-col>
<v-col cols="12" md="6">
<v-text-field
id="field-advisor" v-model="form.advisor" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.advisor" label="指導老師" placeholder="例如:林教授"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('advisor')" />
</v-col>
<v-col cols="12" md="6">
<v-text-field
id="field-email" v-model="form.email" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.email" label="Email" placeholder="name@school.edu"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('email')" />
</v-col>
<v-col cols="12" md="6">
<v-text-field
id="field-phone" v-model="form.phone" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.phone" label="電話" placeholder="例如:02-2345-6789"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('phone')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-status" v-model="form.status" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.status"
:items="statuses" label="狀態" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('status')" />
</v-col>
</v-row>
</v-form>
</template>
<template #actions>
<v-spacer />
<v-btn :disabled="isSaving" variant="text" @click="requestCloseDialog">取消</v-btn>
<v-btn v-if="isEditMode" color="error" :disabled="isSaving" variant="tonal" @click="requestDeleteCurrent">
刪除
</v-btn>
<v-btn
v-if="!isViewMode" color="primary" :disabled="!isDirty || isLoading" :loading="isSaving"
variant="flat" @click="requestSaveConfirmation">
儲存
</v-btn>
<v-btn v-else color="primary" variant="flat" @click="requestCloseDialog">關閉</v-btn>
</template>
</mnt-dialog-card>
</div>
</v-overlay>
</teleport>
<common-confirm-dialog
v-model="confirmCloseVisible" confirm-color="error" confirm-text="關閉不儲存" message="目前有尚未儲存的內容,確定要關閉嗎?"
title="未儲存變更" @confirm="confirmClose" />
<common-confirm-dialog
v-model="confirmSaveVisible" :confirm-loading="isSaving" confirm-text="確認儲存" max-width="520"
title="確認儲存變更" @confirm="confirmSave">
<div v-if="saveSummary.length > 0" class="d-flex flex-column ga-2">
<div v-for="item in saveSummary" :key="item.label" class="d-flex flex-column">
<div class="text-caption text-medium-emphasis">{{ item.label }}</div>
<div v-if="item.before !== null" class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.before) }">
{{ item.before }}
</span>
</div>
<div class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.after) }">
{{ item.after }}
</span>
</div>
</div>
</div>
<div v-else class="text-body-2">目前沒有可儲存的變更</div>
</common-confirm-dialog>
<common-confirm-dialog
v-model="confirmDeleteVisible" confirm-color="error" confirm-text="確定刪除"
:message="`確定要刪除 ${pendingDeleteLabel} 嗎?此操作無法復原。`" title="確認刪除" @confirm="confirmDelete" />
<common-confirm-dialog
v-model="confirmSwitchVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換為檢視模式將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmSwitch" />
<common-confirm-dialog
v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換到其他資料將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmNavigate" />
<!-- 成功提示 -->
<v-snackbar v-model="snackbarVisible" color="success" location="bottom right" :timeout="2200">
儲存成功
</v-snackbar>
</template>
<script setup lang="ts">
import { computed, nextTick, ref } from 'vue'
import { useDisplay } from 'vuetify'
import CommonConfirmDialog from '@/components/maintenance/CommonConfirmDialog.vue'
import MntDialogCard from '@/components/maintenance/MntDialogCard.vue'
import MntPageCards from '@/components/maintenance/MntPageCards.vue'
import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue'
import { type StudentRecord, useStudentStore } from '@/stores/students'
// 下拉選項:系所/年級/入學年度/狀態
const departments = ['資訊工程', '企業管理', '應用外語', '視覺設計', '財務金融']
const gradeOptions = [
{ title: '大一', value: 1 },
{ title: '大二', value: 2 },
{ title: '大三', value: 3 },
{ title: '大四', value: 4 },
{ title: '研究所', value: 5 },
]
const enrollYears = [2024, 2023, 2022, 2021, 2020, 2019]
const statuses = ['在學', '休學', '畢業']
const { smAndUp } = useDisplay()
// 表格欄位設定(含固定欄與排序)
const tableHeaders = computed(() => [
{ title: '學號', key: 'studentId', sortable: true, fixed: smAndUp.value && 'start' as const, width: 120 },
{ title: '姓名', key: 'name', sortable: true, fixed: smAndUp.value && 'start' as const, width: 100 },
{ title: '系所', key: 'department', sortable: true, width: 140 },
{ title: '年級', key: 'grade', sortable: true, width: 90 },
{ title: '入學年度', key: 'enrollYear', sortable: true, width: 110 },
{ title: '已修學分', key: 'credits', sortable: true, width: 110 },
{ title: 'Email', key: 'email', sortable: true, width: 200 },
{ title: '電話', key: 'phone', sortable: true, width: 140 },
{ title: '指導老師', key: 'advisor', sortable: true, width: 110 },
{ title: '狀態', key: 'status', sortable: true, width: 90 },
{ title: '操作', key: 'actions', sortable: false, fixed: smAndUp.value && 'end' as const, width: 'auto', cellProps: { class: 'px-0 bg-background' } },
])
// 查詢條件(示意用,未接 API)
const search = ref({
studentId: '',
name: '',
department: '',
grade: null as number | null,
status: '',
})
// 查詢區塊是否展開
const searchPanelOpen = ref(false)
// 透過 store 管理 Demo 資料與 CRUD
const studentStore = useStudentStore()
const students = computed(() => studentStore.students)
type StudentPayload = Omit<StudentRecord, 'id'>
// 彈窗狀態與流程控制
const dialogVisible = ref(false)
const editingId = ref<number | null>(null)
const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const isLoading = ref(false)
const isSaving = ref(false)
// 各種確認彈窗
const confirmCloseVisible = ref(false)
const confirmSaveVisible = ref(false)
const confirmDeleteVisible = ref(false)
const confirmSwitchVisible = ref(false)
const confirmNavigateVisible = ref(false)
// UI 回饋
const snackbarVisible = ref(false)
const highlightedId = ref<number | null>(null)
// 防止快速切換導致的異步覆蓋
const loadSequence = ref(0)
// 暫存待處理的目標
const pendingDelete = ref<StudentRecord | null>(null)
const pendingSwitchTarget = ref<StudentRecord | null>(null)
const pendingNavigateTarget = ref<StudentRecord | null>(null)
// 表單資料與初始快照(用於 dirty 判斷)
const form = ref({
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
})
const initialForm = ref({ ...form.value })
// 欄位錯誤訊息(僅保存一則)
const fieldErrors = ref<Record<string, string[]>>({
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
})
// 表單欄位簡單排版(無分組)
// 彈窗標題/副標題
const dialogTitle = computed(() => {
if (dialogMode.value === 'view') return '檢視資料示範'
if (dialogMode.value === 'edit') return '修改資料示範'
return '新增資料示範'
})
const dialogSubtitle = computed(() => {
if (!editingId.value) return ''
return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}`
})
const isEditMode = computed(() => dialogMode.value === 'edit')
const isViewMode = computed(() => dialogMode.value === 'view')
// 是否有修改(用於啟用儲存與提示)
const isDirty = computed(
() => JSON.stringify(form.value) !== JSON.stringify(initialForm.value),
)
// 載入/儲存時鎖定、檢視模式 readonly
const isFormLocked = computed(() => isLoading.value || isSaving.value)
const isFormReadonly = computed(() => isViewMode.value)
// 目前筆數索引(用於導覽)
const currentRecordIndex = computed(() =>
students.value.findIndex((item) => item.id === editingId.value),
)
const currentEditingRecord = computed(
() => students.value.find((item) => item.id === editingId.value) || null,
)
const hasPrevRecord = computed(() => currentRecordIndex.value > 0)
const hasNextRecord = computed(
() => currentRecordIndex.value >= 0 && currentRecordIndex.value < students.value.length - 1,
)
const pendingDeleteLabel = computed(() => {
if (!pendingDelete.value) return '這筆資料'
return `${pendingDelete.value.studentId} ${pendingDelete.value.name}`
})
const saveSummary = computed(() => {
const labels: Record<string, string> = {
studentId: '學號',
name: '姓名',
department: '系所',
grade: '年級',
enrollYear: '入學年度',
credits: '已修學分',
advisor: '指導老師',
email: 'Email',
phone: '電話',
status: '狀態',
}
const before = initialForm.value
const after = form.value
const entries = Object.keys(labels).map((key) => {
const beforeValue = before[key as keyof typeof before]
const afterValue = after[key as keyof typeof after]
return {
key,
label: labels[key],
before: editingId.value ? formatSummaryValue(key, beforeValue) : null,
after: formatSummaryValue(key, afterValue),
}
})
if (!editingId.value) return entries
return entries.filter((entry) => entry.before !== entry.after)
})
// 重設查詢條件
function resetSearch () {
search.value = {
studentId: '',
name: '',
department: '',
grade: null,
status: '',
}
}
// 重設表單與錯誤狀態
function resetForm () {
form.value = {
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
}
initialForm.value = { ...form.value }
clearAllErrors()
}
// 新增:開啟彈窗,使用預設值
function openAddDialog () {
loadSequence.value += 1
dialogMode.value = 'create'
editingId.value = null
resetForm()
isLoading.value = false
dialogVisible.value = true
}
// 編輯:先開彈窗,資料載入後填入
function openEditDialog (student: StudentRecord) {
loadSequence.value += 1
const sequence = loadSequence.value
dialogMode.value = 'edit'
editingId.value = student.id
dialogVisible.value = true
isLoading.value = true
clearAllErrors()
setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = {
studentId: student.studentId,
name: student.name,
department: student.department,
grade: student.grade,
enrollYear: student.enrollYear,
credits: student.credits,
advisor: student.advisor,
email: student.email,
phone: student.phone,
status: student.status,
}
initialForm.value = { ...form.value }
isLoading.value = false
}, 350)
}
// 檢視:只讀模式並預設展開所有分組
function openViewDialog (student: StudentRecord) {
loadSequence.value += 1
const sequence = loadSequence.value
dialogMode.value = 'view'
editingId.value = student.id
dialogVisible.value = true
isLoading.value = true
clearAllErrors()
setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = {
studentId: student.studentId,
name: student.name,
department: student.department,
grade: student.grade,
enrollYear: student.enrollYear,
credits: student.credits,
advisor: student.advisor,
email: student.email,
phone: student.phone,
status: student.status,
}
initialForm.value = { ...form.value }
isLoading.value = false
}, 350)
}
// 依方向切換上一筆/下一筆
function openAdjacentRecord (direction: 'prev' | 'next') {
if (!isViewMode.value && !isEditMode.value) return
const index = currentRecordIndex.value
if (index < 0) return
const targetIndex = direction === 'prev' ? index - 1 : index + 1
const target = students.value[targetIndex]
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 切換到第一筆/最後一筆
function openEdgeRecord (position: 'first' | 'last') {
if (!isViewMode.value && !isEditMode.value) return
if (students.value.length === 0) return
const target = position === 'first' ? students.value[0] : students.value.at(-1)
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 檢視 → 編輯(直接切換)
function switchToEditMode () {
if (!isViewMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
openEditDialog(current)
}
// 編輯 → 檢視(若 dirty 需確認)
function switchToViewMode () {
if (!isEditMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
if (isDirty.value) {
pendingSwitchTarget.value = current
confirmSwitchVisible.value = true
return
}
openViewDialog(current)
}
// 確認切換為檢視模式
function confirmSwitch () {
const target = pendingSwitchTarget.value
pendingSwitchTarget.value = null
confirmSwitchVisible.value = false
if (!target) return
openViewDialog(target)
}
// 確認切換到其他資料
function confirmNavigate () {
const target = pendingNavigateTarget.value
pendingNavigateTarget.value = null
confirmNavigateVisible.value = false
if (!target) return
openEditDialog(target)
}
// 先檢核再提示儲存確認
async function requestSaveConfirmation () {
if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return
clearAllErrors()
const errors = validateForm()
if (errors.length > 0) {
for (const error of errors) {
fieldErrors.value[error.field] = [error.message]
}
await nextTick()
const firstError = errors[0]
if (firstError) scrollToField(firstError.field)
return
}
confirmSaveVisible.value = true
}
// 儲存確認後才真正送出
function confirmSave () {
confirmSaveVisible.value = false
saveStudent()
}
// 寫入資料(Demo:直接更新列表)
async function saveStudent () {
if (isSaving.value || isLoading.value) return
isSaving.value = true
await new Promise((resolve) => setTimeout(resolve, 450))
const payload = {
studentId: form.value.studentId.trim(),
name: form.value.name.trim(),
department: form.value.department,
grade: form.value.grade,
enrollYear: form.value.enrollYear,
credits: form.value.credits,
advisor: form.value.advisor.trim(),
email: form.value.email.trim(),
phone: form.value.phone.trim(),
status: form.value.status,
} as StudentPayload
if (editingId.value) {
const updated = studentStore.updateStudent(editingId.value, payload)
if (updated) highlightedId.value = editingId.value
} else {
const createdId = studentStore.addStudent(payload)
highlightedId.value = createdId
}
initialForm.value = { ...form.value }
dialogVisible.value = false
snackbarVisible.value = true
isSaving.value = false
window.setTimeout(() => {
highlightedId.value = null
}, 1600)
}
// 刪除:先提示確認
function requestDeleteConfirmation (student: StudentRecord) {
pendingDelete.value = student
confirmDeleteVisible.value = true
}
// 編輯模式刪除目前資料
function requestDeleteCurrent () {
const current = currentEditingRecord.value
if (!current) return
requestDeleteConfirmation(current)
}
// 確認刪除後,若正在編輯該筆則關閉彈窗
function confirmDelete () {
if (!pendingDelete.value) return
const deletedId = pendingDelete.value.id
studentStore.removeStudent(deletedId)
pendingDelete.value = null
confirmDeleteVisible.value = false
if (editingId.value === deletedId) {
closeDialog()
}
}
// 狀態顏色映射
function statusColor (status: string) {
if (status === '在學') return 'success'
if (status === '休學') return 'warning'
if (status === '畢業') return 'secondary'
return 'default'
}
// 年級顯示字串
function gradeLabel (grade: number) {
return gradeOptions.find((option) => option.value === grade)?.title ?? `年級 ${grade}`
}
// 列高亮(儲存後提示位置)
function rowProps (data: { item: StudentRecord }) {
return {
class: data.item.id === highlightedId.value ? 'is-highlighted' : '',
}
}
function clearAllErrors () {
fieldErrors.value = {
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
}
}
function clearFieldError (field: string) {
if (!fieldErrors.value[field]?.length) return
fieldErrors.value[field] = []
}
function validateForm () {
const errors: Array<{ field: string; message: string }> = []
const studentId = form.value.studentId.trim()
const name = form.value.name.trim()
const email = form.value.email.trim()
const credits = form.value.credits
if (!studentId) errors.push({ field: 'studentId', message: '請輸入學號' })
if (!name) errors.push({ field: 'name', message: '請輸入姓名' })
if (!form.value.department) errors.push({ field: 'department', message: '請選擇系所' })
if (!form.value.grade) errors.push({ field: 'grade', message: '請選擇年級' })
if (!form.value.enrollYear) errors.push({ field: 'enrollYear', message: '請選擇入學年度' })
if (credits === null || Number.isNaN(credits)) {
errors.push({ field: 'credits', message: '請輸入已修學分' })
} else if (credits < 0) {
errors.push({ field: 'credits', message: '已修學分不可小於 0' })
}
if (!form.value.status) errors.push({ field: 'status', message: '請選擇狀態' })
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ field: 'email', message: 'Email 格式不正確' })
}
const duplicate = students.value.find(
(item) => item.studentId === studentId && item.id !== editingId.value,
)
if (studentId && duplicate) {
errors.push({ field: 'studentId', message: '學號已存在,請確認是否重複' })
}
return errors
}
const errorSummary = computed(() => {
const entries = Object.entries(fieldErrors.value).flatMap(([field, messages]) =>
messages.map((message) => ({ field, message })),
)
return entries.slice(0, 3)
})
function scrollToField (field: string) {
const target = document.getElementById(`field-${field}`)
if (!target) return
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
function requestCloseDialog () {
if (isDirty.value && !isSaving.value) {
confirmCloseVisible.value = true
return
}
closeDialog()
}
function confirmClose () {
confirmCloseVisible.value = false
closeDialog()
}
function closeDialog () {
dialogVisible.value = false
isLoading.value = false
isSaving.value = false
confirmSaveVisible.value = false
confirmSwitchVisible.value = false
confirmNavigateVisible.value = false
dialogMode.value = 'create'
editingId.value = null
clearAllErrors()
resetForm()
}
function handleDialogVisibility (nextValue: boolean) {
if (nextValue) {
dialogVisible.value = true
return
}
requestCloseDialog()
}
const isPlaceholderValue = (value: string | null) => value === '—'
function formatSummaryValue (key: string, value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '—'
if (key === 'grade') return gradeLabel(Number(value))
return String(value)
}
</script>
<style scoped>
.dialog-overlay :deep(.v-overlay__content) {
height: 100vh;
display: flex;
justify-content: flex-end;
width: 100vw;
max-width: 100vw;
}
.dialog-panel {
width: 760px;
max-width: 100%;
height: 100vh;
background: rgb(var(--v-theme-surface));
padding: 12px;
box-shadow: -12px 0 24px rgba(0, 0, 0, 0.18);
display: flex;
}
.dialog-actions {
position: sticky;
bottom: 0;
background: rgba(var(--v-theme-surface), 0.95);
border-top: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
z-index: 1;
}
.dialog-title {
position: sticky;
top: 0;
background: rgba(var(--v-theme-surface), 0.95);
border-bottom: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
z-index: 2;
}
.student-table {
overflow: auto;
}
.student-table :deep(table) {
min-width: 1400px;
}
.student-table :deep(th),
.student-table :deep(td) {
white-space: nowrap;
}
.student-table :deep(.v-data-table-column--fixed),
.student-table :deep(.v-data-table-column--fixed-end) {
background: rgb(var(--v-theme-surface));
}
.student-table :deep(.v-data-table-column--fixed-last-start)::after {
content: '';
position: absolute;
top: 0;
right: -5px;
bottom: 0;
width: 5px;
box-shadow: inset 10px 0 8px -8px rgba(0, 0, 0, 0.15);
}
.student-table :deep(.v-data-table-footer) {
padding: 4px 0 0;
}
/* 直線 */
/* .student-table :deep(.v-data-table-column--first-fixed-end),
.student-table :deep(.v-data-table-column--last-fixed) {
border-left: none !important;
border-right: none !important;
} */
.form-readonly :deep(.v-field) {
pointer-events: none;
}
tbody tr.is-highlighted {
animation: row-highlight 1.6s ease-out;
}
@keyframes row-highlight {
0% {
background-color: rgba(var(--v-theme-primary), 0.18);
}
100% {
background-color: transparent;
}
}
</style>