Vite Vue 2025

Vite Vue 安裝

版本號
node v22.14.0 && npm 11.4.2

參考資料:
https://vite.dev/guide/

安裝

1
npm create vite@latest 資料名稱
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
> npx
> "create-vite" vite_vue_demo_project

│
◆ Select a framework:
│ ● Vanilla
│ ○ Vue
│ ○ React
│ ○ Preact
│ ○ Lit
│ ○ Svelte
│ ○ Solid
│ ○ Qwik
│ ○ Angular
│ ○ Marko
│ ○ Others
└

│
◇ Select a framework:
│ Vue
│
◇ Select a variant:
│ TypeScript
│
◇ Use rolldown-vite (Experimental)?:
參考資料:https://cn.vite.dev/guide/rolldown
│ Yes
│
◆ Install with npm and start now?
│ ● Yes / ○ No

Angular 之GoogleDrive 串接圖牆

Google Cloud 申請 OAuth

Google Console 畫面
前往 Google Cloud Console 的「憑證」頁面:

建立一個新專案 > 新增專案

啟用API服務

建立憑證 => OAuth用戶端ID

• 確認「OAuth 2.0 用戶端 ID」清單中確實有這組 ID,且沒有被刪除或停用。

• 選取「網頁應用程式」。

• 填寫名稱。

• 當你要使用oauth=> 已授權重先導向 =>
https://developers.google.com/oauthplayground

• 取得Google client_id 用戶端編號

• 「手動新增範圍」的輸入框
資料存取權 => 「新增或移除範圍」
複製並貼上這兩行完整的網址(一行一個):

「更新所選範圍」

「手動新增範圍」的輸入框

1
2
3
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.readonly

獲取到
client_id
project_id
client_secret

安裝 @types/gapi , @types/gapi.client.drive , @types/google.accounts

安裝指令:

1
2
npm install --save-dev @types/gapi @types/gapi.client.drive @types/google.accounts

src/index.html 引入accounts.google.com

1
<script src="https://accounts.google.com/gsi/client" async defer></script>

src/app/services/google-drive.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import { Injectable, inject, signal } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, map } from 'rxjs';
import { environment } from '../../../environment'
export interface DriveFile {
id: string
name: string
mimeType: string
thumbnailLink?: string // 新增:Google Drive 自動產生的縮圖網址
webViewLink?: string // 新增:Google Drive 的檢視網址
}
@Injectable({ providedIn: 'root' })
export class GoogleDriveService {
private http = inject(HttpClient);
// 替換成你的 Client ID
private readonly CLIENT_ID =environment.GOOGLE_CLIENT_ID;
// 權限範圍:drive.file 僅能存取此 App 建立的檔案;若要讀取所有檔案請改用
private readonly SCOPES = 'https://www.googleapis.com/auth/drive.file';

private readonly DRIVE_API_URL = 'https://www.googleapis.com/drive/v3';

private tokenClient!: google.accounts.oauth2.TokenClient;

// 使用 Signal 儲存 Token,完美支援 Zoneless 與 OnPush
accessToken = signal<string | null>(null);

constructor() {
console.log(environment.production ? 'Production' : '開發中');
console.log('GoogleDriveService', environment.GOOGLE_CLIENT_ID);
this.initTokenClient();
}
// 初始化 GAPI 與 GIS
private initTokenClient(): void {
// 確保 gis script 已載入
if (typeof google !== 'undefined') {
// 初始化 GAPI Client (負責呼叫 Drive API)
this.tokenClient = google.accounts.oauth2.initTokenClient({
client_id: this.CLIENT_ID,
scope: this.SCOPES,
callback: (response) => {
if (response.access_token) {
this.accessToken.set(response.access_token);
}
},
});
}
}

// 觸發 Google 登入與授權視窗
login(): void {
if (!this.tokenClient) this.initTokenClient();
this.tokenClient.requestAccessToken({ prompt: 'consent' });
}

// 登出並撤銷 Token
logout(): void {
const token = this.accessToken();
if (token) {
google.accounts.oauth2.revoke(token, () => {
this.accessToken.set(null);
});
}
}

// 取得檔案列表
/*
你在程式中設定的 SCOPES 是 https://googleapis.com。這個權限只允許你的應用程式讀取「由這個應用程式建立或開啟」的檔案,不會顯示你 Google Drive 裡原本就存在的其他檔案。如果你想測試讀取列表是否成功,請先用你的 uploadFile 上傳一個檔案,再按「讀取檔案列表」就能看到它了。
*/
listFiles(): Observable<{ files: DriveFile[] }> {
// console.log('取得檔案列表', files)
const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
});
const redFilesApi = `${this.DRIVE_API_URL}/files`;
const params = {
pageSize: '10',
fields: 'files(id,name,mimeType,thumbnailLink,webViewLink)',
}
//
console.log('取得檔案列表 params', params)
return this.http.get<{ files: DriveFile[] }>(redFilesApi, {headers, params: params,});
}
// 刪除檔案或資料夾
deleteFile(fileId: string): Observable<void> {
const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
});
const deleteFileApi = `${this.DRIVE_API_URL}/files/${fileId}`;
return this.http.delete<void>(deleteFileApi, {
headers,
});
}
// 新增:將檔案設為「知道連結的任何人皆可檢視」,以便分享網址
makeFilePublic(fileId: string): Observable<unknown> {
const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
'Content-Type': 'application/json',
});
const makeFilePublicApi = `${this.DRIVE_API_URL}/files/${fileId}/permissions`;
return this.http.post(
makeFilePublicApi,
{
role: 'reader',
type: 'anyone',
},
{ headers }
);
}
// 建立資料夾 (可選填 parentId 指定上層資料夾)
createFolder(folderName: string, parentId?: string): Observable<DriveFile> {
const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
'Content-Type': 'application/json',
});

const metadata: { name: string; mimeType: string; parents?: string[] } = {
name: folderName,
mimeType: 'application/vnd.google-apps.folder',
};

// 如果有指定上層資料夾 ID,則建立在該資料夾內;未指定則建立在雲端硬碟根目錄
if (parentId) {
metadata.parents = [parentId];
}

return this.http.post<DriveFile>(`${this.DRIVE_API_URL}/files`, metadata, {
headers,
});
}

// 上傳檔案 (Multipart 上傳範例)
uploadFile(file: File, folderId?: string): Observable<DriveFile> {
const metadata: { name: string; mimeType: string; parents?: string[] } = {
name: file.name,
mimeType: file.type,
};

// 指定上傳目標資料夾
if (folderId) {
metadata.parents = [folderId];
}

const formData = new FormData();
formData.append(
'metadata',
new Blob([JSON.stringify(metadata)], { type: 'application/json' })
);
formData.append('file', file);

const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
});
// Multipart 上傳,Request Headers 中的 Content-Type: multipart/form-data
const apiUploadFileMultipart = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart';
// 單純上傳檔案內容
const apiuploadFileMedia ='https://www.googleapis.com/upload/drive/v3/files?uploadType=media'
return this.http.post<DriveFile>(
apiUploadFileMultipart,
formData,
{ headers }
);
}
// 取得圖片的本地預覽網址 (Blob URL)
getImagePreviewUrl(fileId: string): Observable<string> {
const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
});

return this.http
.get(`${this.DRIVE_API_URL}/files/${fileId}`, {
headers,
params: { alt: 'media' }, // 關鍵參數:要求回傳檔案實際內容而非 JSON
responseType: 'blob', // 指定回傳二進位資料
})
.pipe(map((blob) => URL.createObjectURL(blob)));
}
}

ng g c imageArea

src/app/image-area.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import { Component, inject, signal, computed} from '@angular/core'
import { GoogleDriveService, DriveFile } from '../services/google-drive'
@Component({
imports: [],
standalone: true,
selector: 'app-image-area',
styleUrl: './image-area.css',
templateUrl: './image-area.html',
})
export class ImageArea {
driveService = inject(GoogleDriveService);
// 儲存所有檔案與資料夾
files = signal<DriveFile[]>([]);
// 新增:儲存目前預覽的圖片網址與檔名
previewUrl = signal<string | null>(null);
previewFileName = signal<string>('');
// 自動過濾出「資料夾」,供上傳時的下拉選單使用
folders = computed(() =>
this.files().filter(
(f) => f.mimeType === 'application/vnd.google-apps.folder'
)
);

// 取得列表
loadFiles(): void {
this.driveService.listFiles().subscribe({
next: (res) => this.files.set(res.files || []),
error: (err) => console.error('讀取列表失敗', err),
});
}

// 點擊圖片檔案時觸發預覽
onPreviewImage(file: DriveFile): void {
// 釋放上一次產生的本地網址,避免記憶體洩漏
const oldUrl = this.previewUrl();
if (oldUrl) {
URL.revokeObjectURL(oldUrl);
}

this.previewFileName.set(file.name);
this.driveService.getImagePreviewUrl(file.id).subscribe({
next: (url) => this.previewUrl.set(url),
error: (err) => console.error('載入圖片預覽失敗', err),
});
}

// 關閉預覽
closePreview(): void {
const oldUrl = this.previewUrl();
if (oldUrl) {
URL.revokeObjectURL(oldUrl);
}
this.previewUrl.set(null);
}
// 建立資料夾
onCreateFolder(folderName: string): void {
const trimmedName = folderName.trim();
if (!trimmedName) return;

this.driveService.createFolder(trimmedName).subscribe({
next: (newFolder) => {
alert(`資料夾「${newFolder.name}」建立成功!`);
this.loadFiles(); // 建立後自動更新列表
},
error: (err) => console.error('建立資料夾失敗', err),
});
}

// 選擇並上傳檔案
onFileSelected(event: Event, folderId: string): void {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;

// 若 folderId 為空字串則傳入 undefined (存至根目錄)
this.driveService.uploadFile(file, folderId ).subscribe({
next: (uploadedFile) => {
alert(`檔案「${uploadedFile.name}」上傳成功!`);
this.loadFiles(); // 上傳後自動更新列表
input.value = ''; // 清空 input 以便重複選取同一個檔案
},
error: (err) => console.error('上傳檔案失敗', err),
});
}
// 刪除檔案
onDeleteFile(file: DriveFile): void {
if (!confirm(`確定要刪除「${file.name}」嗎?此動作無法復原。`)) {
return;
}

this.driveService.deleteFile(file.id).subscribe({
next: () => {
// 從畫面列表直接移除該項目,不需重新打一次列表 API
this.files.update((list) => list.filter((item) => item.id !== file.id));

// 如果剛好正在預覽這張圖片,一併關閉預覽
if (this.previewFileName() === file.name) {
this.closePreview();
}
},
error: (err) => console.error('刪除失敗', err),
});
}
// 設定公開權限並複製網址
onCopyLink(file: DriveFile): void {
this.driveService.makeFilePublic(file.id).subscribe({
next: () => {
// 優先使用 API 回傳的 webViewLink,若無則組裝標準檢視網址
// (若你希望複製的是「可直接嵌入 <img> 的圖片直連網址」,可改用 `https://googleusercontent.com{file.id}`)
const shareUrl = file.webViewLink || `https://google.com{file.id}/view`;

navigator.clipboard.writeText(shareUrl).then(() => {
alert(`已開啟公開檢視並複製網址:\n${shareUrl}`);
});
},
error: (err) => console.error('設定權限或複製網址失敗', err),
});
}
}

image-area.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<p>圖片上傳</p>
<div class="drive-container">
<!-- 登入 / 登出控制區 -->
<div class="auth-section">
@if (!driveService.accessToken()) {
<button (click)="driveService.login()">登入 Google Drive</button>
} @else {
<button (click)="driveService.logout()">Google Drive登出</button>
}
</div>

<!-- 登入後才顯示操作區塊 -->
@if (driveService.accessToken()) {

<!-- 1. 建立資料夾區塊 -->
<div class="action-box">
<h3>建立資料夾</h3>
<input
type="text"
#folderInput
placeholder="輸入資料夾名稱"
/>
<button (click)="onCreateFolder(folderInput.value); folderInput.value = ''">
建立資料夾
</button>
</div>

<!-- 2. 上傳檔案區塊 -->
<div class="action-box">
<h3>上傳檔案</h3>
<label>
目標位置:
<select #targetFolderSelect>
<option value="">根目錄 (My Drive)</option>
@for (folder of folders(); track folder.id) {
<option [value]="folder.id">📁 {{ folder.name }}</option>
}
</select>
</label>
<label type="button" for="uploadInput" class="uploadInput">
<input
id="uploadInput"
type="file"
(change)="onFileSelected($event, targetFolderSelect.value)"
/>
</label>
<label for="file-upload" class="upload-dropzone">
<div class="upload-icon-wrapper" aria-hidden="true">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" height="24px" width="24px" fill="#1f1f1f"><path d="M6.5,20q-2.27,0-3.89-1.57T1,14.58q0-1.95 1.18-3.47T5.25,9.15q0.63-2.3 2.5-3.72T12,4q2.93,0 4.96,2.04T19,11q1.73,0.2 2.86,1.49T23,15.5q0,1.88-1.31,3.19T18.5,20H13q-0.82,0-1.41-0.59T11,18V12.85L9.4,14.4L8,13l4-4l4,4l-1.4,1.4L13,12.85V18h5.5q1.05,0 1.78-0.73T21,15.5t-0.72-1.78T18.5,13H17V11q0-2.08-1.46-3.54T12,6Q9.93,6 8.46,7.46T7,11H6.5q-1.45,0-2.47,1.02T3,14.5t1.03,2.48T6.5,18H9v2H6.5ZM12,13Z"/></svg>
</div>
<input id="file-upload" type="file" accept=".jpg,.jpeg,.png,.pdf" hidden />
</label>

</div>

<!-- 3. 相簿與檔案格狀列表 -->
<div class="list-box">
<h3>檔案與相簿列表 <button (click)="loadFiles()">重新整理</button></h3>
</div>
<div class="list_picture_row">
@for (item of files(); track item.id) {
<div class="single_img">

<!-- 縮圖或圖示顯示區 -->
<div class="single_img_thum">
@if (item.mimeType === 'application/vnd.google-apps.folder') {
<span style="font-size: 48px;">📁</span>
} @else if (item.thumbnailLink) {
<!-- 直接顯示 Google Drive 提供的縮圖,點擊可看大圖 -->
<img
[src]="item.thumbnailLink"
[alt]="item.name"
referrerpolicy="no-referrer"
(click)="onPreviewImage(item)"
/>
} @else {
<span style="font-size: 48px;">📄</span>
}
</div>

<!-- 檔案名稱 -->
<div class="file_name" [title]="item.name">
{{ item.name }}
</div>
<!-- 操作按鈕區:複製網址 & 刪除 -->
<div style="display: flex; gap: 6px; justify-content: center; border-top: 1px solid #eee; padding-top: 8px;">
@if (item.mimeType !== 'application/vnd.google-apps.folder') {
<button
(click)="onCopyLink(item)"
style="flex: 1; font-size: 12px; padding: 4px; cursor: pointer;"
title="設為公開並複製網址">
複製網址
</button>
}
<button
(click)="onDeleteFile(item)"
style="flex: 1; font-size: 12px; padding: 4px; color: #d32f2f; cursor: pointer;"
title="永久刪除">
刪除
</button>
</div>
</div>
} @empty {
<p>目前沒有檔案或資料夾</p>
}
</div>
}
</div>

image-area.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
p{
padding: 20px;
}
.drive-container{
padding: 20px;
}
.action-box, .list-box{
display: flex;
align-items: center;
margin-top: 35px;
}
.action-box input ,
.action-box select{
border:2px solid #666;
padding: 12px 8px;
margin-left: 20px;
}
.action-box input[type="file"]
.action-box label{
margin-left: 20px;
}
.auth-section button,.action-box button ,.list-box button {
background-color: #666;
color:#fff;
padding: 12px 8px;
margin-left: 20px;
}
.list_picture_row{
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 16px;
margin-top: 12px;
}
.list_picture_row .single_img{
border: 1px solid #ddd;
border-radius: 8px;
padding: 10px;
text-align: center;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.list_picture_row .single_img .single_img_thum{
height: 120px;
display: flex;
align-items: center;
justify-content:center;
overflow: hidden;
background: #f9f9f9;
border-radius: 4px;
margin-bottom: 8px;
}
.list_picture_row .single_img .single_img_thum img{
width: 100%;
height: 100%;
object-fit: cover;
cursor: pointer;
}

.file_name{
font-size: 13px;
word-break: break-all;
overflow: hidden;
text-overflow:ellipsis;
display: -webkit-box;
line-clamp: 2;
-webkit-line-clamp: 2;
-webkit-box-orient:vertical;
}

/**/
input[type="file"] {
display: none;
}

.upload-dropzone {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
padding: 0px 42px;
border: 2px solid #666;
cursor: pointer;
transition: border-color 0.2s, background-color 0.2s;
text-align: center;
margin-left: 20px;
}

.upload-dropzone:hover {
color:#fff;
border-color: #333;
background-color: #333;
}

.upload-icon-wrapper {
width: 25px;
height: 44px;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 3px;
transition: transform 0.2s, background-color 0.2s, color 0.2s;
}

.upload-dropzone:hover .upload-icon-wrapper {
color: #fff;
transform: translateY(-1px);
}
.upload-dropzone:hover .upload-icon-wrapper svg {
fill: #fff;
}
.upload-svg {
width: 24px;
height: 24px;
}

.upload-title {
font-size: 15px;
font-weight: 600;
color: #0f172a;
}

.upload-hint {
font-size: 13px;
color: #64748b;
margin-top: 4px;
}
先登入

Nuxt4 安裝

清除 npx 快取

確保 Nuxt CLI 不存在快取或版本上的差異,可以清除快取來重新安裝。

1
npx clear-npx-cache

Nuxt 安裝

Node版本號 22.13.1
安裝指令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// pnpm
pnpm create nuxt@latest <project-name>
// yarn
yarn create nuxt <project-name>
// npm
npm create nuxt@latest <project-name>

create-nuxt@3.34.0
Ok to proceed? (y)


> npx
> create-nuxt nuxt_demo_project


.d$b.
i$$A$$L .d$b
.$$F` `$$L.$$A$$.
j$$' `4$$:` `$$.
j$$' .4$: `$$.
j$$` .$$: `4$L
:$$:____.d$$: _____.:$$:
`4$$$$$$$$P` .i$$$$$$$$P`

┌ Welcome to Nuxt!
│載入模板
◇ Templates loaded
◇ 從快取載入模板
◇ Templates loaded
│
│◆ 您想使用哪一個範本?
◆ Which template would you like to use?
content – 內容驅動網站

○ minimal – Nuxt 4 的極簡配置(建議)
│ ● minimal – Minimal setup for Nuxt 4 (recommended)
○ module – Nuxt 模組
│ ○ module – Nuxt module
●. * ui – 使用 Nuxt UI 的應用
│ ○ ui – App using Nuxt UI
◇ 在 nuxt4_demo_project 中建立項目
◇ Creating project in nuxt4_demo_project
◇ 已下載最小模板
◇ Downloaded minimal template
│

◆ 您想使用哪個軟體套件管理器?
◆ Which package manager would you like to use?
│ ● npm (current)
│ ○ pnpm
│ ○ yarn
│ ○ bun
│ ○ deno
◆ 初始化 Git 倉庫?
Initialize git repository?
│ No
│
◇ 已安裝依賴項
◇ Dependencies installed
│
│ ◇ 是否要瀏覽並安裝模組?
◇ Would you like to browse and install modules?
│ Yes
│
│ ◇ 已載入模組
◇ Modules loaded
│
│ ◇ 搜尋並選擇模組:
│ 0 items selected
│
└ ✨ Nuxt 專案是使用最小範本建立的。
└ ✨ Nuxt project has been created with the minimal template.

╭── 👉 Next steps ───────────╮
│ │
│ › cd demo_nuxt_project │
│ › npm run dev │
│ │
╰────────────────────────────╯
larahuang@larahuang Nuxt % cd demo_nuxt_project
larahuang@larahuang demo_nuxt_project % npm run dev

Nuxt 4.4.2 (with Nitro 2.13.3, Vite 7.3.2 and Vue 3.5.32)
下午1:57:17
➜ Local: http://localhost:3000/
➜ Network: use --host to expose

預設監聽 Port: 3000,若因為衝突或有需要做調整可以使用這個參數

1
2
3
npm run dev -- -p 5173
# 等價
npx nuxi dev -p 5173

建立 .env 檔案:在專案根目錄建立 .env 檔案,定義您的環境變數。

1
2
API_BASE_URL=https://example.com

清除自動產生的 Nuxt 檔案和快取

1
npx nuxi cleanup

Nuxt 3 實戰筆記

nuxt4架構

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
├── .nuxt/                 # Nuxt開發中,根據目錄結構生成。
├── .output/ # Nuxt build 後的輸出目錄(用於部署)
├── .env # 環境配置檔
├── plugins/ # 套件
├── public/ # 靜態公開檔案
├── server/ # 放後端邏輯
│ └── api/
│ └── order.js # 對應 /api/order
├── app.vue # Nuxt 應用入口點
├── app.vue # 入口點
├── layouts/ # 自訂佈局
├── middleware/ # 中介層邏輯
├── assets/ # 靜態資源
├── components/ # Vue 元件
├── composables/ # 邏輯函式
├── content/ # 資料檔案
├── pages/ # 頁面檔案
├── nuxt.config.ts # Nuxt 配置設定檔(支援 TypeScript)
├── package.json # 套件與指令設定
├── tsconfig.json # TypeScript 設定
└── README.md # 專案說明

安裝Tailwindcss

參考Nuxt UI 官網

安裝 Nuxt UI 套件

1
npm install @nuxt/ui tailwindcss --save

將 Nuxt UI 模組新增到您的系統中nuxt.config.ts

1
2
3
export default defineNuxtConfig({
modules: ['@nuxt/ui']
})

在您的 CSS 中匯入 Tailwind CSS 和 Nuxt UI

app/assets/css/main.css nuxt.config.ts

1
2
3
// app/assets/css/main.css 
@import "tailwindcss";
@import "@nuxt/ui";

.vscode/settings.json

1
2
3
4
5
6
7
8
9
10
11
{
"files.associations": {
"*.css": "tailwindcss"
},
"editor.quickSuggestions": {
"strings": "on"
},
"tailwindCSS.classAttributes": ["class", "ui"],
"tailwindCSS.classFunctions": ["defineAppConfig"]
}

安裝. ElementPLus

1
2
3
npm i @element-plus/nuxt -D
npm i --save element-plus
npm i --save @element-plus/icons-vue

https://github.com/element-plus/element-plus-nuxt-starter/tree/main

配置

nuxt.config.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
export default defineNuxtConfig({
// 模組新增到您的系統中nuxt
modules: [
'@nuxt/eslint',
'@nuxt/ui',
'@element-plus/nuxt'
],
// 開發者工具
devtools: {
enabled: true
},
// 樣式
css: ['~/assets/scss/main.scss'],
// 路由規則
routeRules: {
// 預渲染
'/': { prerender: true }
},
// 相容性日​​期
compatibilityDate: '2025-01-15',
// 相容性日​​期
vite: {
css: {
// 預處理器選項:
preprocessorOptions: {
scss: {
// 附加數據
additionalData: `@use "@/assets/scss/element/index.scss" as element;`
}
}
}
},
// elementPlus
elementPlus: {
icon: 'el-icon',
importStyle: 'scss',
themes: ['dark']
}
})

Nuxt4 Layouts 佈局

Layouts

參考資料
透過在你的 app.vue 中加入 來啟用 Layouts。
app/app.vue

1
2
3
4
5
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>

新增一個 ~/layouts/default.vue
app/layouts/default.vue
在佈局檔案中,頁面的內容將會顯示在 元件中。

1
2
3
4
5
6
<template>
<div>
<p>所有頁面共享一些預設佈局內容</p>
<slot />
</div>
</template>

具名佈局(Named Layout)

1
2
3
-| layouts/
---| default.vue
---| custom.vue

你可以在頁面中使用 custom 佈局
pages/about.vue

1
2
3
4
5
6
7
8
9
10
11
<script setup lang="ts">
declare module 'nuxt/app' {
interface NuxtLayouts {
'custom': unknown
}
}
// ---cut---
definePageMeta({
layout: 'custom',
})
</script>

你可以使用 的 name 屬性直接覆寫所有頁面的預設佈局。
app/app.vue

1
2
3
4
5
6
7
8
9
10
<script setup lang="ts">
// 您可能會根據 API 呼叫或登入狀態來選擇此項目。
const layout = 'custom'
</script>

<template>
<NuxtLayout :name="layout">
<NuxtPage />
</NuxtLayout>
</template>

Nuxt4 環境變數

1.在根目錄新增.env

1
2
API_BASE_URL=https://example.com
DB_PASSWORD=your_secret_password

2.nuxt.config.ts設定

在 nuxt.config.ts 中綁定變數

1
2
3
4
5
6
7
8
9
10
11
12
export default defineNuxtConfig({
//
runtimeConfig: {
// 伺服器端私有變數
dbPassword: process.env.DB_PASSWORD,

// 公開變數(也會暴露給客戶端)
public: {
apiBaseUrl: process.env.API_BASE_URL,
}
}
})

3. process問題

解決方法,安裝 @types/node

1
npm i --save-dev @types/node 

專案根目錄建立檔案 server/api/test.ts:

1
2
3
4
5
6
7
8
export default defineEventHandler((event) => {
const config = useRuntimeConfig()

// 這會在您的終端機(Terminal)印出,而不是瀏覽器
// console.log('伺服器端讀取密碼:', config.dbPassword)

return { success: true }
})

在頁面或組件中讀取

範例放在app.vue

1
2
3
4
5
6
7
8
9
<script setup lang="ts" >
const runtimeConfig = useRuntimeConfig()

// 讀取公開變數(客戶端與伺服器皆可見)
console.log('讀取公開變數(客戶端與伺服器皆可見)',runtimeConfig.public.apiBaseUrl)

console.log('伺服器端讀取密碼:',runtimeConfig.dbPassword)

</script>

Nuxt4 如何部署vercel

nuxt如何部署vercel

一、修改本機專案配置 Nitro 預設:在 nuxt.config.ts 中將 nitro 預設為 vercel。
1.

1
2
3
4
5
6
7
//打字稿
導出預設的defineNuxtConfig({
硝基:{
預設:'vercel'
}
})

2.提交程式碼:確保您的程式碼已經透過 Git 初始化並自動至 GitHub、GitLab 或 Bitbucket 倉庫。
二、Vercel導入與部署登入Vercel儀表板。點選新增新建,選擇項目。授權並選擇您的GitHub倉庫,點擊匯入。 Vercel環境變數中填入。點選部署,等待建置即可完成上線。
nuxt.config.ts 中加入硝基.vercel.config 參數。環境變數管理:如果您使用 dotenv,可以透過 Dotenv Nuxt 官方的 Nuxt 部署至 Vercel 指南或 iT 邦幫忙 Vercel 部署攻略。

SAP UI5 專案架構

SAP UI5專案架構

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
├── node_modules              # 
webapp/ # 應用程式的核心根目錄
│
├── controller/ # 邏輯控制層 (Controller)
│ ├── App.controller.js
│ └── Main.controller.js
│
├── view/ # 介面顯示層 (View,通常為 XML 格式)
│ ├── App.view.xml
│ └── Main.view.xml
│
├── model/ # 資料模型層 (Model,處理本地或全域資料)
│ ├── formatter.js # 欄位格式化工具
│ └── models.js # 初始化模型的工廠方法
│
├── i18n/ # 多國語言語系檔
│ ├── i18n.properties # 預設語系
│ └── i18n_zh_TW.properties
│
├── css/ # 自訂樣式表 (選填)
│ └── style.css
│
├── Component.js # 應用的入口組件,負責初始化與路由啟動
├── manifest.json # 核心元數據描述文件(描述配置、資料源、路由)
└── index.html # 獨立運行的本地測試入口網頁
├── .gitignore git版控
├── package.json # 套件與指令設定
└── README.md # 專案說明

核心架構元件解析

  • manifest.json (App Descriptor):
  1. 核心配置中心:定義應用程式的識別碼(ID)、版本、所依賴的 UI5 核心庫,以及多國語言檔路徑。
  2. 資料源與模型宣告:在此處定義與後端溝通的 dataSources(例如 SAP OData 服務),並直接綁定至全域 models。
  3. 路由配置 (Routing):定義導頁邏輯(Routes)與對應的顯示目標(Targets),實現單頁應用(SPA)的切換。
  • Component.js
  1. 應用啟動點:繼承自 sap.ui.core.UIComponent。
  2. 自動載入:框架會引導此檔案自動讀取 manifest.json。它的主要職責是例項化應用的根視圖(Root View)並初始化路由服務。
  • View (視圖層):
  1. 宣告式 UI:強烈建議使用 XML 格式(如 Main.view.xml)。
  2. 核心職責:僅負責佈局與控制項定義(如表格、輸入框、按鈕),不包含任何業務邏輯,確保介面與邏輯分離。
  • Controller (控制層):
  1. 行為處理:使用 JavaScript 撰寫(如 Main.controller.js),負責處理視圖上觸發的事件(如點擊按鈕、輸入驗證)。
  2. 資料操作:透過控制項獲取模型,或將後端資料更新至模型中。
  • Model (模型層與資料綁定):
    雙向綁定:支援 JSONModel(本地雙向)、ResourceModel(多國語言 i18n)以及 ODataModel(後端伺服器資料同步)。

兩種主要的開發架構型態

  1. SAP UI5 Free-style (自由開發):
  2. 依循上述標準 MVC 架構,開發者擁有極高的 UI 客製化彈性。
  3. 適用於業務邏輯極度特殊、現有標準元件無法滿足的企業流程。
  4. SAP Fiori Elements (配置驅動開發):
  5. 無代碼/低代碼 UI:開發者不需要手動撰寫 View 和 Controller。
  6. 元數據驅動:完全依賴後端 OData 服務的註解 (Annotations)與元數據來自動渲染標準的 Fiori 頁面(例如:List Report、Object Page)。
  7. 適用於高標準化、講求快速交付的增刪查改(CRUD)應用。

manifest.json 解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
{
"_version": "1.12.0",
"sap.app": {
"id": "my.app", // 應用的唯一識別碼
"i18n": "i18n/i18n.properties", // 多國語言文字檔的路徑
"title": "{{appTitle}}", // 應用標題,對應 i18n 裡的 key
"description": "{{appDescription}}",
"applicationVersion": {
"version": "1.0.0"
},
"dataSources": {
"orderApi": {
"url": "https://script.google.com/macros/s/AKfycby3VIvl_TU4O_KoFUNXlvfINS0Lv1CEZuU5AoY7YU9JaFTgZ2x1f1lvStjoIuUldREFKw/exec",
"type": "JSON"
}
}
},
"sap.ui": {
"technology": "UI5",
"icons": {},
"deviceTypes": {
"desktop": true,
"tablet": true,
"phone": true
}
},
"sap.ui5": {
"rootView": {
"viewName": "my.app.view.Main", // 應用的第一個根視圖(通常只包含 sap.m.App 控制項)
"type": "XML",
"async": true,
"id": "app"
},
"resources": {
"css": [
{
"uri": "css/style.css"
}
]
},
"dependencies": {
"minUI5Version": "1.71.66",
"libs": {
"sap.ui.core": {},
"sap.m": {}, // 必備的行動與桌面端核心 UI 庫
"sap.tnt": {},
"sap.f": {}
}
},
"handleValidation": true,
"contentDensities": {
"compact": true,
"cozy": true
},
"models": {
"i18n": {. // 宣告全域多國語言模型
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "uxc.integration.i18n.i18n",
"async": true
}
},
"": { // 空白字串代表「預設模型」,通常綁定主要 OData 服務
"dataSource": "mainService",
"preload": true,
"settings": {
"v2Mode": true,
"defaultBindingMode": "TwoWay" // 設定雙向綁定(畫面改,資料改)
}
},
"ui": {
"type": "sap.ui.model.json.JSONModel"
}
},
"routing": { ... }
}
}

參考資料

index.html
引入 SAPUI5 核心庫
全部語法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SAPUI5 1.71 Google Sheets CRUD 系統</title>
<!-- 引入 SAPUI5 核心庫 src="https://sdk.openui5.org/resources/sap-ui-core.js" -->

<script
src="https://sdk.openui5.org/resources/sap-ui-core.js"
data-sap-ui-theme="sap_fiori_3"
data-sap-ui-resourceroots='{"my.app": "./"}'
data-sap-ui-compatVersion="edge"
data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
data-sap-ui-async="true"
>
</script>
</head>
<body class="sapUiBody" id="content">
<div data-sap-ui-component data-name="my.app"></div>
</body>
</html>

Component.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sap.ui.define([
"sap/ui/core/UIComponent"
], function (UIComponent) {
"use strict";
return UIComponent.extend("my.app.Component", {
metadata: {
manifest: "json"
},
init: function () {
UIComponent.prototype.init.apply(this, arguments);

}
});
});



Main.view.xml 如同 html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<mvc:View
controllerName="my.app.controller.Main"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
xmlns:f="sap.ui.layout.form"
xmlns:core="sap.ui.core">
<App>
<Page title="SAPUI5 1.71.66 Google Sheets RESTful CRUD 系統">
<content><!-- 使用 SimpleForm 構建表單 -->
<f:SimpleForm
editable="true"
layout="ResponsiveGridLayout"
labelSpanXL="3"
labelSpanL="3"
labelSpanM="3"
labelSpanS="12"
adjustLabelSpan="false"
emptySpanXL="4"
emptySpanL="4"
emptySpanM="4"
emptySpanS="0"
columnsXL="1"
columnsL="1"
columnsM="1"
singleContainerFullWidth="true">
<f:content>
<VBox>
<Label text="產品名稱" required="true" />
<Input
placeholder="請輸入產品名稱..."

/>

<Label text="活動區域" required="true" />
<Select
id="zoneSelect"
selectedKey="{/selectedZone}"
items="{path: '/zones'}"
change="onZoneChange"
>
<items>
<!-- key 是傳給後台的值,text 是顯示給使用者看的文字 -->
<core:Item key="{key}" text="{text}" />
</items>
</Select>

<!-- 職業 -->
<Label text="職業" required="true" />
<Select placeholder="請選擇職業"
selectedKey="{/selectedTags}"
items="{path: '/tags'}"
change="onTagsChange"
>
<core:Item key="{tagId}" text="{tagName}" />

</Select>
<Label text="活動時間" required="true" />
<!-- 運用 HBox 將日期與時間選擇器並排 -->
<HBox alignItems="Center">
<DatePicker
placeholder="Pick a date" valueFormat="yyyy-MM-dd"
displayFormat="yyyy/MM/dd"
change="onDateChange"
/>
<Text text="-" class="sapUiTinyMarginEnd" />
<TimePicker placeholder="Pick a time" />
</HBox>
<!-- 即時送達 -->
<Label text="即時送達" />
<Switch state="false" type="AcceptReject" />

<!-- 活動地點 -->
<Label text="活動地點" required="true" />
<SegmentedButton selectedKey="home">
<items>
<SegmentedButtonItem key="home" text="Home" />
<SegmentedButtonItem key="company" text="Company" />
<SegmentedButtonItem key="school" text="School" />
</items>
</SegmentedButton>
<!-- 活動類型 -->
<Label text="活動類型" required="true" />
<VBox>
<HBox>
<CheckBox text="公司" class="sapUiLargeMarginEnd" />
<CheckBox text="車站" />
</HBox>
<HBox>
<CheckBox text="辦公室" class="sapUiLargeMarginEnd" />
<CheckBox text="捷運" />
</HBox>

<!-- 資源 -->
<Label text="資源" required="true" />
<RadioButtonGroup columns="2">
<buttons>
<RadioButton text="Sponsorship" />
<RadioButton text="Venue" />
</buttons>
</RadioButtonGroup>
<!-- Activity form -->
<Label text="Activity form" required="true" />
<TextArea rows="4" growing="true" width="100%" />
</VBox>
<Button
text="送出資料"
press="onButtonClick"
type="Emphasized" />
</VBox>
</f:content>
</f:SimpleForm>
</content>
</Page>
</App>
</mvc:View>

Main.controller.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
"sap/m/MessageBox",
"sap/m/MessageToast",
"sap/m/Dialog",
"sap/m/Button",
"sap/ui/layout/form/SimpleForm",
"sap/m/Label",
"sap/m/Input",
], function (Controller, JSONModel, MessageBox, MessageToast, Dialog, Button, SimpleForm, Label, Input)
{
"use strict";

return Controller.extend("my.app.controller.Main", {
// 初始化
onInit: function ()
{
var oDataSource = this.getOwnerComponent().getMetadata().getManifestEntry("sap.app").dataSources.orderApi;
this._sBaseUrl = oDataSource.url;
console.log('this._sBaseUrl', this._sBaseUrl)
this.onReadData()
// 1. 準備下拉選單的資料來源
var oData = {
// Select 的資料
zones: [
{ key: "Z1", text: "台北總部" },
{ key: "Z2", text: "台中分部" },
{ key: "Z3", text: "高雄辦事處" }
],
// 預設選中台北
selectedZone: "Z1",

// ComboBox 的資料
owners: [
{ id: "EMP001", name: "王大同" },
{ id: "EMP002", name: "李小美" },
{ id: "EMP003", name: "張三豐" }
],
selectedOwner: "",

// MultiComboBox 的資料
tags: [
{ tagId: "T1", tagName: "科技" },
{ tagId: "T2", tagName: "金融" },
{ tagId: "T3", tagName: "教育" }
],
selectedTags: ["T1"] // 預設多選勾選科技與金融
};

// 2. 建立 JSON 模型並設置到 View 上
var oModel = new JSONModel(oData);
this.getView().setModel(oModel);
},

onReadData: function ()
{
jQuery.ajax({
url: this._sBaseUrl ,
method: "GET",
dataType: "json",
success: function (aData) {
console.log('aData',aData)
// 將拿到的陣列塞入 JSONModel
this._oQuizModel.setProperty("", aData);
oTable.setBusy(false);
MessageToast.show("題庫加載完畢!");
}.bind(this),
error: function (oError) {
oTable.setBusy(false);
MessageBox.error("加載失敗,原因:" + oError.responseText);
}
});
},
// 下拉選單數值改變時的事件監聽
onZoneChange: function (oEvent)
{
console.log('onZoneChange',oEvent)
var oSelectedItem = oEvent.getParameter("selectedItem");
var sSelectedKey = oSelectedItem.getKey();
var sSelectedText = oSelectedItem.getText();

console.log("使用者選擇了 Key: " + sSelectedKey + " , Text: " + sSelectedText);
},
onTagsChange: function (oEvent)
{
console.log('onTagsChange',oEvent)
var oSelectedItem = oEvent.getParameter("selectedItem");
var sSelectedKey = oSelectedItem.getKey();
var sSelectedText = oSelectedItem.getText();
console.log("使用者選擇了 Key: " + sSelectedKey + " , Text: " + sSelectedText);
},
onDateChange: function (oEvent) {
// === 方法 A:取得格式化後的字串(例如 "2026-07-13")===
// 這是最常用的做法,可以直接拿來傳給後端 API
var sValue = oEvent.getParameter("value");
var bValid = oEvent.getParameter("valid"); // 檢查使用者輸入的日期是否合法

if (!bValid) {
MessageToast.show("請輸入正確的日期格式!");
return;
}

// === 方法 B:取得原生 JS Date 物件 ===
// 如果你需要拿這個日期去做計算(例如計算天數、判斷是否大於今天)
var oDatePicker = oEvent.getSource();
var oDateObject = oDatePicker.getDateValue(); // 得到標準的 Date 物件

// 測試輸出
console.log("字串格式 (value):", sValue);
console.log("JS 物件 (dateValue):", oDateObject);

MessageToast.show("您選擇了:" + sValue);
},
onCreatePress: function () {
MessageToast.show("表單已成功創建!");
},

onResetPress: function () {
MessageToast.show("表單已重置。");
// 在此處加入清除各控制項欄位值的邏輯
}
})
})

使用node 來啟動

package.json 套件與指令設定
scripts 使用ui5 serve –port 8080 -o index.html

1
2
3
4
5
6
7
8
9
10
11
12
{
"name": "sapui5-google-sheets-crud-app",
"version": "1.0.0",
"description": "SAPUI5 1.71 Google Sheets App with UI5 Tooling Local Proxy",
"scripts": {
"start": "ui5 serve --port 8080 -o index.html"
},
"devDependencies": {
"@ui5/cli": "^3.0.0",
"ui5-middleware-simpleproxy": "^3.1.2"
}
}

npm 安裝會產生一個node_modules資料夾

1
npm install 

啟動

1
node run start

SAP UI5 表單

主選單 BaseController.js

controller/BaseController.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/core/routing/History"
], function (Controller, History) {
"use strict";

return Controller.extend("my.navigation.app.controller.BaseController", {
// 封裝獲取 Router 的方法
getRouter: function () {
return this.getOwnerComponent().getRouter();
},

// 全域導頁按鈕事件
onNavToHome: function () { this.getRouter().navTo("RouteHome"); },

onNavToProduct: function () { this.getRouter().navTo("RouteProduct"); },

onNavToForms: function () { this.getRouter().navTo("RouteForms"); },

onNavToContact: function () { this.getRouter().navTo("RouteContact"); }
});
});

Label
在 SAP UI5 中,sap.m.Label 是一種專門用來顯示「文字標籤」的 UI 控制項(Control)。它最常見的用途是放在輸入框(如 sap.m.Input)、下拉選單或核取方塊的前面或上方,用來提示使用者該欄位需要填寫或選擇什麼內容。
  • 核心特性與重要屬性
  • text 屬性:用來設定標籤要顯示的文字。通常會透過資料綁定 (Data Binding) 連接到 i18n 國際化語系檔案,以支援多國語言。
  • labelFor 屬性: 這是 Label 最關鍵的關聯屬性。你需要將它設定為對應輸入控制項的 id(例如:labelFor="myInputId")。這樣做有兩大好處:
    • 無障礙螢幕閱讀器支援 (Accessibility):讓盲人或視障使用者使用的螢幕閱讀器能正確讀出該輸入框的含義。
    • 點擊導向:使用者用滑鼠點擊該 Label 文字時,游標會自動聚焦(Focus)到對應的輸入框中。
  • required 屬性:當設為 true 時,標籤文字的前面或後面會自動出現一個紅色的星號(*),用來視覺化提示使用者該欄位為「必填欄位」。
  • 樣式調整::支援透過屬性微調設計,例如設定文字加粗(design="Bold")或文字對齊方式(textAlign)。
程式碼範例 (XML View)在 SAP UI5 的檢視畫面(View)中,通常會結合佈局控制項(如 Form)一起使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:f="sap.ui.layout.form">
<f:SimpleForm editable="true">
<f:content>
<!-- 宣告 Label,並使用 labelFor 綁定到下方的 Input 控制項 -->
<Label text="使用者名稱" required="true" labelFor="usernameInput" />
<Input id="usernameInput" placeholder="請輸入您的姓名" />

<Label text="電子郵件" labelFor="emailInput" />
<Input id="emailInput" type="Email" />
</f:content>
</f:SimpleForm>
</mvc:View>

controller/Forms.controller.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/** 引入相關元件BaseController 主選單,
* MessageToast:內建提示工具:在使用 MessageToast 之前,必須先在 Controller 的最上方(AMD 載入模組區)將 sap/m/MessageToast 引入。=>如果主選單已經引入就不需要重複引入
*/
sap.ui.define([
"my/navigation/app/controller/BaseController",
"sap/m/MessageToast",
"sap/ui/model/json/JSONModel",
"sap/m/MessageBox",
"sap/m/Dialog",
"sap/m/Button",
"sap/ui/layout/form/SimpleForm",
"sap/m/Label",
"sap/m/Input",
], function (BaseController, MessageToast,JSONModel,MessageBox,Dialog, Button, SimpleForm, Label, Input) {
"use strict";

return BaseController.extend("my.navigation.app.controller.Forms", {
onInit: function ()
{
var oDataSource = this.getOwnerComponent().getMetadata().getManifestEntry("sap.app").dataSources.orderApi;
this._sBaseUrl = oDataSource.url;
console.log('this._sBaseUrl', this._sBaseUrl)
this.onReadData()

// 1. 準備下拉選單的資料來源
var oData = {
// Select 的資料
zones: [
{ key: "Z1", text: "台北總部" },
{ key: "Z2", text: "台中分部" },
{ key: "Z3", text: "高雄辦事處" }
],
// 預設選中台北
selectedZone: "Z1",

// ComboBox 的資料
owners: [
{ id: "EMP001", name: "王大同" },
{ id: "EMP002", name: "李小美" },
{ id: "EMP003", name: "張三豐" }
],
selectedOwner: "",

// MultiComboBox 的資料
tags: [
{ tagId: "T1", tagName: "科技" },
{ tagId: "T2", tagName: "金融" },
{ tagId: "T3", tagName: "教育" }
],
selectedTags: ["T1"] // 預設多選勾選科技與金融
};

// 2. 建立 JSON 模型並設置到 View 上
var oModel = new JSONModel(oData);
this.getView().setModel(oModel);
},
// 讀取
onReadData: function () {
jQuery.ajax({
url: this._sBaseUrl ,
method: "GET",
dataType: "json",
success: function (aData) {
console.log('aData',aData)
// 將拿到的陣列塞入 JSONModel
this._oQuizModel.setProperty("", aData);
oTable.setBusy(false);
MessageToast.show("題庫加載完畢!");
}.bind(this),
error: function (oError) {
oTable.setBusy(false);
MessageBox.error("加載失敗,原因:" + oError.responseText);
}
});
},
// 下拉選單數值改變時的事件監聽
onZoneChange: function (oEvent)
{
console.log('onZoneChange',oEvent)
var oSelectedItem = oEvent.getParameter("selectedItem");
var sSelectedKey = oSelectedItem.getKey();
var sSelectedText = oSelectedItem.getText();

console.log("使用者選擇了 Key: " + sSelectedKey + " , Text: " + sSelectedText);
},
onTagsChange: function (oEvent)
{
console.log('onTagsChange',oEvent)
var oSelectedItem = oEvent.getParameter("selectedItem");
var sSelectedKey = oSelectedItem.getKey();
var sSelectedText = oSelectedItem.getText();
console.log("使用者選擇了 Key: " + sSelectedKey + " , Text: " + sSelectedText);
},
onDateChange: function (oEvent) {
// === 方法 A:取得格式化後的字串(例如 "2026-07-13")===
// 這是最常用的做法,可以直接拿來傳給後端 API
var sValue = oEvent.getParameter("value");
var bValid = oEvent.getParameter("valid"); // 檢查使用者輸入的日期是否合法

if (!bValid) {
MessageToast.show("請輸入正確的日期格式!");
return;
}

// === 方法 B:取得原生 JS Date 物件 ===
// 如果你需要拿這個日期去做計算(例如計算天數、判斷是否大於今天)
var oDatePicker = oEvent.getSource();
var oDateObject = oDatePicker.getDateValue(); // 得到標準的 Date 物件

// 測試輸出
console.log("字串格式 (value):", sValue);
console.log("JS 物件 (dateValue):", oDateObject);

MessageToast.show("您選擇了:" + sValue);
},
onCreatePress: function () {
MessageToast.show("表單已成功創建!");
},

onResetPress: function () {
MessageToast.show("表單已重置。");
// 在此處加入清除各控制項欄位值的邏輯
},
onSubmit: function () {
MessageToast.show("表單已成功送出,我們將盡快與您聯絡!");
}
});
});

view/Forms.view.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<mvc:View
controllerName="my.navigation.app.controller.Forms"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
xmlns:f="sap.ui.layout.form"
xmlns:core="sap.ui.core">
<Page showHeader="true" title="聯絡我們">
<OverflowToolbar width="100%" class="sapUiContentPadding">
<Button text="首頁" press="onNavToHome" />
<Button text="產品介紹" press="onNavToProduct" />
<Button text="表單" press="onNavToForms" />
<Button text="聯絡我們" type="Emphasized" press="onNavToContact" />
</OverflowToolbar>
<content>
<VBox class="sapUiMediumMargin">
<Title text="表單" titleStyle="H1" class="sapUiSmallMarginBottom" />
<f:SimpleForm
editable="true"
layout="ResponsiveGridLayout"
labelSpanXL="3"
labelSpanL="3"
labelSpanM="3"
labelSpanS="12"
adjustLabelSpan="false"
emptySpanXL="4"
emptySpanL="4"
emptySpanM="4"
emptySpanS="0"
columnsXL="1"
columnsL="1"
columnsM="1"
singleContainerFullWidth="true">
<f:content>
<VBox>
<Label text="產品名稱" required="true" />
<Input
placeholder="請輸入產品名稱..."
/>

<Label text="活動區域" required="true" />
<Select
id="zoneSelect"
selectedKey="{/selectedZone}"
items="{path: '/zones'}"
change="onZoneChange"
>
<items>
<!-- key 是傳給後台的值,text 是顯示給使用者看的文字 -->
<core:Item key="{key}" text="{text}" />
</items>
</Select>

<!-- 職業 -->
<Label text="職業" required="true" />
<Select placeholder="請選擇職業"
selectedKey="{/selectedTags}"
items="{path: '/tags'}"
change="onTagsChange"
>
<core:Item key="{tagId}" text="{tagName}" />

</Select>
<Label text="活動時間" required="true" />
<!-- 運用 HBox 將日期與時間選擇器並排 -->
<HBox alignItems="Center">
<DatePicker
placeholder="Pick a date" valueFormat="yyyy-MM-dd"
displayFormat="yyyy/MM/dd"
change="onDateChange"
/>
<Text text="-" class="sapUiTinyMarginEnd" />
<TimePicker placeholder="Pick a time" />
</HBox>
<!-- 即時送達 -->
<Label text="即時送達" />
<Switch state="false" type="AcceptReject" />

<!-- 活動地點 -->
<Label text="活動地點" required="true" />
<SegmentedButton selectedKey="home">
<items>
<SegmentedButtonItem key="home" text="Home" />
<SegmentedButtonItem key="company" text="Company" />
<SegmentedButtonItem key="school" text="School" />
</items>
</SegmentedButton>
<!-- 活動類型 -->
<Label text="活動類型" required="true" />
<VBox>
<HBox>
<CheckBox text="公司" class="sapUiLargeMarginEnd" />
<CheckBox text="車站" />
</HBox>
<HBox>
<CheckBox text="辦公室" class="sapUiLargeMarginEnd" />
<CheckBox text="捷運" />
</HBox>

<!-- 資源 -->
<Label text="資源" required="true" />
<RadioButtonGroup columns="2">
<buttons>
<RadioButton text="Sponsorship" />
<RadioButton text="Venue" />
</buttons>
</RadioButtonGroup>
<!-- Activity form -->
<Label text="Activity form" required="true" />
<TextArea rows="4" growing="true" width="100%" />
</VBox>
<Button
text="送出資料"
press="onButtonClick"
type="Emphasized" />
</VBox>
</f:content>
</f:SimpleForm>
</VBox>
</content>
</Page>
</mvc:View>