Vue 3 Admin Dashboard from Scratch: A 19-Step Guide with Real Gotchas
Practical Guide to Building a Frontend Project at a Big Company - From Empty Folder to a Running Admin Dashboard
This is a hands-on, learn-as-you-go guide. The table of contents supports click-to-jump: click a section title to jump to it, and click
[↑ Back to TOC](#toc)at the end of each section to return.
Table of Contents (Click to Jump)
Foundation
- 0. Before You Start: Environment and Conventions
- 1. Initialize Project: One Command to Build the Skeleton
- 2. Code Standards: ESLint + Prettier + TypeScript Strict Mode
- 3. Directory Planning and Path Aliases
Core Capabilities (Each with a Minimal Example)
- 4. Element Plus: Menu + Table + Pagination
- 5. Vue Router: Routing and Lazy Loading
- 6. Pinia: Global State and Persistence
- 7. Axios: Request Wrapping
- 8. TanStack Query: Server State
- 9. i18n: Chinese/English Switching
- 10. Permission Directive: Button Show/Hide
- 11. ECharts: Line Chart
- 12. Day.js: Time Utilities
- 13. CSS Variables: Theme Switching
- 14. Mock: Fake Data
- 15. Testing: Vitest Unit Tests
Wrap-up
- 16. Commit Validation: Git Hooks
- 17. Build and Verification Command Quick Reference
- 18. Pitfall Log (Real Issues Encountered and Fixed)
- 19. What Else Can Be Added
Quick Reference: Cross-Check with Theory Notes
| This Book (Hands-On) | Theory Notes (Decisions) |
|---|---|
| Chapters 1-3: Initialization / Standards / Directory | Chapter 1 Engineering Skeleton, Chapter 2 Commit Constraints, Chapter 3 Type Contracts |
| Chapter 4: Element Plus | Chapter 5 Component Library and Style Foundation |
| Chapter 5: Routing | Chapter 6 Routing and SPA Skeleton |
| Chapters 6, 7: Pinia / Axios | Chapter 7 State Management, Chapter 9 Request Wrapping, Chapter 10 Login State |
| Chapter 8: TanStack Query | Chapter 8 Server State and Data Layer |
| Chapters 9, 10: i18n / Permissions | Chapter 12 Internationalization, Chapter 13 Permission System |
| Chapters 11-14: Charts / Time / Theme / Mock | Chapters 15-18 Corresponding Capabilities |
| Chapters 15, 16: Testing / Git Hooks | Chapter 21 Testing System, Chapter 2 Commit Constraints |
| Chapter 19: Expansion Directions | Chapters 19-39 Engineering / Security / Advanced Chapters |
Each chapter title has a line indicating the corresponding theory. This book deliberately builds only minimal loops; production-grade approaches (dynamic routing, SSO, i18n governance, security specifics, etc.) are covered in the theory notes.
0. Before You Start: Environment and Conventions
🔗 Corresponding Theory: Chapters 1 and 2 (Engineering Skeleton / Commit Constraints)
Tested environment for this project (version differences may cause minor discrepancies; see Chapter 18 for pitfalls):
| Tool | Version | Check Command |
|---|---|---|
| Node | v22.22.2 | node --version |
| pnpm | 12.15.0 | pnpm --version |
| Git | 2.55.0 | git --version |
Write version constraints into package.json (when changing machines or CI, a version mismatch will cause immediate errors, which is more reliable than verbal agreements):
"engines": {
"node": ">=22.0.0",
"pnpm": ">=10.0.0"
}
Use with .nvmrc (generated in Chapter 1): nvm use switches to the project's required Node version.
Three Reproducibility Essentials:
- This project uses
pnpm-lock.yaml— it must be committed to git. CI installs withpnpm install --frozen-lockfileto ensure everyone has exactly the same dependency versions. - The
enginesfield locks the major versions of Node / pnpm (see above). - The build script whitelist
pnpm-workspace.yamlmust also be committed (starting with pnpm 12, see Pitfall 1):
# pnpm-workspace.yaml — Only packages in this list are allowed to run postinstall scripts
allowBuilds:
simple-git-hooks: true
vue-demi: true
Conventions:
- Run all commands in the
E:\ai_work\06_learning_demo\demodirectory (firstcdinto it). - Use pnpm as the package manager consistently; do not mix npm/yarn.
- Run
pnpm buildafter each step to confirm nothing is broken.
1. Initialize Project: One Command to Build the Skeleton
🔗 Corresponding Theory: Chapter 1 (Project Initialization)
1.1 Create the Project
The target folder is empty; use create-vite to generate a Vue 3 + TypeScript template in the current directory (.):
# Enter the target directory (change to your own path)
cd E:\ai_work\06_learning_demo\demo
# One command to generate the project skeleton: latest=latest version, vue-ts=Vue3+TypeScript template, --yes=skip interactive prompts
pnpm create vite@latest . --template vue-ts --yes
After execution, you'll see the scaffolded files:
├── .gitignore # git ignore rules (dependencies, build artifacts)
├── .vscode/ # Editor recommended configuration
├── index.html # Page entry HTML
├── package.json # Project configuration and dependencies
├── public/ # Static assets (not processed by bundler)
├── src/
│ ├── App.vue # Root component
│ ├── main.ts # Application entry
│ ├── style.css # Global styles
│ └── components/ # Component directory
├── tsconfig.json # TS config entry
├── tsconfig.app.json # Application code TS config
├── tsconfig.node.json # Build tool TS config
└── vite.config.ts # Vite config
1.2 Install Dependencies, Lock Node Version, and Initialize Git
# Install dependencies; generates pnpm-lock.yaml (must be committed for team consistency)
pnpm install
# Lock Node version so teammates/CI use the same version, avoiding 'works locally but breaks on production'
echo v22.22.2 > .nvmrc
# Initialize git repository
git init
📌 The
pnpm-lock.yamlgenerated bypnpm installmust be committed. In the future, install withpnpm install --frozen-lockfile; if the lock and package.json are inconsistent, it will throw an error, preventing 'works locally but breaks on production'.⚠️ The
latestincreate-vite@latestmeans the template version will float: when you rebuild in a few months, the pulled Vue / Vite / TypeScript may be newer than this article, causing new errors. To exactly replicate the results here, replace@latestwith the version tested at that time; usingpnpm create vite@latest . --template vue-tsdirectly will follow the latest version.
1.3 Verify the Baseline Runs
# Build: vue-tsc does type checking + vite bundles
pnpm build
Seeing ✓ built in xxx ms means the base is fine. At this point the page is still Vite's default welcome page.
📷 Step Screenshot: No business pages yet, so skip screenshots. The first meaningful screenshot appears after Chapter 4.
2. Code Standards: ESLint + Prettier + TypeScript Strict Mode
🔗 Corresponding Theory: Chapters 2 and 3 (Code Standards / TypeScript Contracts)
2.1 Install Dependencies
# ESLint core + JS recommended rules + TS support + Vue plugin + globals + Vue's TS parser
pnpm add -D eslint @eslint/js typescript-eslint eslint-plugin-vue globals vue-eslint-parser
# Prettier + bridge package to disable ESLint rules that conflict with Prettier
pnpm add -D prettier eslint-config-prettier
2.2 Prettier Configuration
.prettierrc.json (no semicolons, single quotes, line width 100):
{
"semi": false,
"singleQuote": true,
"printWidth": 100,
"trailingComma": "all"
}
2.3 ESLint Flat Config (Key Point)
eslint.config.js — every line has comments explaining it:
// ESLint flat config (ESLint 9+ default format, no longer needs .eslintrc)
import js from '@eslint/js'
import globals from 'globals'
import vue from 'eslint-plugin-vue'
import vueParser from 'vue-eslint-parser'
import tseslint from 'typescript-eslint'
import prettier from 'eslint-config-prettier'
export default tseslint.config(
// 1) Ignored directories: build artifacts, dependencies, auto-generated type files are not checked
{ ignores: ['dist/**', 'node_modules/**', 'src/auto-imports.d.ts', 'src/components.d.ts'] },
// 2) JS base recommended rules
{ files: ['**/*.js', '**/*.ts'], ...js.configs.recommended },
// 3) TypeScript recommended rules
...tseslint.configs.recommended,
// 4) Vue rules + parser
// Pitfall: flat/recommended uses the default parser which can't parse <script setup lang="ts">
// Must override with a block specifying vue-eslint-parser for templates and tseslint.parser for scripts
...vue.configs['flat/recommended'],
{
files: ['**/*.vue'],
languageOptions: {
parser: vueParser,
parserOptions: { parser: tseslint.parser, ecmaVersion: 'latest', sourceType: 'module' },
globals: globals.browser,
},
},
// 5) Project-specific rules
{
files: ['**/*.{ts,vue}'],
languageOptions: { globals: globals.browser },
rules: {
'vue/multi-word-component-names': 'off', // demo allows single-word component names
'@typescript-eslint/no-explicit-any': 'warn',
},
},
// 6) Must be last: disable rules that conflict with Prettier
prettier,
)
💡 Why this layering: ESLint handles 'is the code correct' (syntax, potential bugs), Prettier handles 'is it pretty' (indentation, quotes). The
prettierconfig in block 6 is placed last to override ESLint's formatting-related rules and prevent conflicts.
2.4 Enable TypeScript Strict Mode
In tsconfig.app.json, add strict: true:
{
"compilerOptions": {
"strict": true, // Enable strict mode: implicit any, null checks, etc. all on
"noUnusedLocals": true, // Unused local variables cause errors
"noUnusedParameters": true
}
}
2.5 Add Scripts to package.json
"scripts": {
"lint": "eslint .", // Check all files
"lint:fix": "eslint . --fix", // Auto-fix what can be fixed
"format": "prettier --write \"src/**/*.{ts,vue,css}\"", // Format
"typecheck": "vue-tsc -b --noEmit", // Type-check only, no bundling
"test": "vitest run" // Run unit tests
}
2.6 Verification
pnpm lint # Should have no errors
pnpm typecheck # Should pass
3. Directory Planning and Path Aliases
🔗 Corresponding Theory: Chapter 1 (Directory Structure Conventions)
3.1 Create Directories by Business Domain
mkdir -p src/{api,components/global,components/business,config,directives,hooks,locales,mock,router,stores,styles,types,utils,views}
After creation, the structure (each chapter will fill files into it):
src/
├── api/ # Interface layer: all requests go out from here
├── components/
│ ├── global/ # Global common components (BaseChart, etc.)
│ └── business/ # Business-specific components
├── config/ # Global configuration (environment variable wrapper)
├── directives/ # Global directives (v-permission)
├── hooks/ # Compositional logic (useXxx)
├── locales/ # Language packs
├── mock/ # Fake data
├── router/ # Route table
├── stores/ # Pinia state repositories
├── styles/ # Theme CSS variables
├── types/ # Type definitions
├── utils/ # Utility functions
└── views/ # Business pages
3.2 Configure the @ Alias
Pitfall: The alias must be configured in two places for Vite to recognize it and TypeScript to recognize it.
vite.config.ts (runtime resolution):
import { fileURLToPath, URL } from 'node:url'
export default defineConfig({
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)), // @ points to the src directory
},
},
})
tsconfig.app.json (type checking recognition):
"paths": {
"@/*": ["./src/*"]
}
💡 TypeScript 6 has deprecated
baseUrl; writepathsdirectly as./src/*(do not addbaseUrl: "."; it will cause an error, see Pitfall).
4. Element Plus: Menu + Table + Pagination
🔗 Corresponding Theory: Chapter 5 (UI Component Library and Style Foundation)
4.1 Install
# Component library + icons
pnpm add element-plus @element-plus/icons-vue
# On-demand import plugins: writing <el-table> auto-imports, no manual registration
pnpm add -D unplugin-vue-components unplugin-auto-import
4.2 Configure On-Demand Imports
vite.config.ts full version:
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
vue(),
// Auto-import Vue APIs (ref/computed) and Element Plus APIs (ElMessage)
AutoImport({
resolvers: [ElementPlusResolver()],
imports: ['vue', 'vue-router', 'pinia'],
dts: 'src/auto-imports.d.ts', // Generate type declarations so TypeScript knows the auto-imported variables
}),
// Auto-import Element Plus components (write el-table in templates and it works)
Components({ resolvers: [ElementPlusResolver()], dts: 'src/components.d.ts' }),
],
resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
server: { port: 5173, host: true },
})
This is Vite's configuration file vite.config.ts, used to tell Vite: when starting or bundling your Vue project, which plugins to load, how to resolve paths, how to auto-import ElementPlus and Vue APIs.
It is read by Vite, not executed by the browser. It runs in a Node environment.
Let's break it down section by section:
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
👉 Import Dependencies
@vitejs/plugin-vue: Vite's core plugin for recognizing.vuesingle-file components; without it Vite can't understand Vue filesfileURLToPath, URL: Node built-in utilities for path aliases (@mapping to src)defineConfig: Vite's utility for TypeScript hints in config; you can return an object directly without it, but it's better to use itAutoImport: Plugin for auto-importing APIs (unplugin-auto-import)Components: Plugin for auto-importing components (unplugin-vue-components)ElementPlusResolver: Resolver for the above two plugins, specifically tailored to ElementPlus
export default defineConfig({
plugins: [
vue(),
The plugins array: all Vite plugins go here, executed in order. vue() enables Vue single-file support.
AutoImport({
resolvers: [ElementPlusResolver()],
imports: ['vue', 'vue-router', 'pinia'],
dts: 'src/auto-imports.d.ts',
}),
✅ AutoImport: auto-import functions, no manual import
imports: ['vue', 'vue-router', 'pinia']means:ref, reactive, computed, watch, useRouter, useRoute, usePinia– you can use them directly in pages without writing importresolvers: [ElementPlusResolver()]also auto-imports ElementPlus functions likeElMessage, ElNotification– just call them, no import neededdts: 'src/auto-imports.d.ts'auto-generates type files so TypeScript doesn't error, otherwise it will sayref not found
Compare: without this plugin, every page needs
import { ref } from 'vue'
Components({ resolvers: [ElementPlusResolver()], dts: 'src/components.d.ts' }),
✅ Components: auto-import components
ElementPlusResolver(): write<el-table /> <el-button />in templates, no import or global registration needed, the plugin auto-imports themdts: generates component type declarations so TypeScript recognizes el components
Compare: without the plugin, you'd need
import ElTable from 'element-plus'and then register it
],
resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
✅ resolve.alias path alias @ is equivalent to the project's src. Writing import User from '@/views/UserManage.vue' is the same as import User from 'src/views/UserManage.vue'. This is the alias you configured in Chapter 3!
Why use
fileURLToPath + new URL? It's the recommended new Vite approach that works with ESM; the old__dirnamecan't be used directly in ESM mode.
server: { port: 5173, host: true },
})
✅ server: development server configuration (only affects pnpm dev, not the build)
port: 5173: local server porthttp://localhost:5173host: true: listen on all network interfaces, so other devices on the same LAN (phones, other computers) can access the page via your internal IP, e.g.,http://192.168.1.100:5173
📌 The overall effect of this configuration (your experience when writing code)
- Write
ref()anywhere, noimport { ref } from 'vue' - Write
<el-button>Button</el-button>in templates, no need to import components - Call
ElMessage.success('Success')directly, no import @/can replace src, shorter paths- Dev server runs on 5173, accessible from LAN
- Auto-generates
.d.tsfiles, TypeScript doesn't show red errors
4.3 Environment Configuration Files
.env.development (development environment):
# Only variables starting with VITE_ are exposed to frontend code
VITE_API_BASE=/api
VITE_APP_TITLE=Management System Demo (Development)
.env.production (production environment):
VITE_API_BASE=/api
VITE_APP_TITLE=Management System Demo
⚠️
VITE_variables are bundled into the JS package, do not put secrets here.
Add type hints for environment variables (high-frequency in admin systems, to avoid import.meta.env.VITE_XXX having no autocompletion or typos not being caught):
src/env.d.ts:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE: string
readonly VITE_APP_TITLE: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
After this, import.meta.env.VITE_API_BASE has autocompletion and type checking; misspelling the variable name will show a red error.
4.4 A Minimal Menu + Table Page
src/views/Layout.vue (sidebar menu, core part excerpt):
<script setup lang="ts">
// Menu item configuration: in a real project, this can come from the backend
const menuItems = [
{ path: '/dashboard', title: 'menu.dashboard', icon: 'House' },
{ path: '/users', title: 'menu.userManage', icon: 'User' },
]
</script>
<template>
<el-container class="layout">
<el-aside width="220px">
<div class="logo">Admin Management System</div>
<el-menu :default-active="$route.path" router>
<el-menu-item v-for="m in menuItems" :key="m.path" :index="m.path">
<el-icon><component :is="m.icon" /></el-icon>
<span>{{ m.title }}</span>
</el-menu-item>
</el-menu>
</el-aside>
<el-main><router-view /></el-main>
</el-container>
</template>
src/views/UserManage.vue table part (excerpt, full version in the repo):
<template>
<el-card>
<el-form inline>
<el-form-item label="Name">
<el-input v-model="keyword" placeholder="Search" clearable @keyup.enter="handleSearch" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleSearch">Search</el-button>
</el-form-item>
</el-form>
<el-table :data="tableData" v-loading="isPending" border stripe style="width: 100%">
<el-table-column prop="id" label="ID" width="80" />
<el-table-column prop="name" label="Name" />
<el-table-column prop="email" label="Email" />
<el-table-column label="Status" width="100">
<template #default="{ row }">
<el-tag :type="row.status === 'active' ? 'success' : 'info'">
{{ row.status === 'active' ? 'Enabled' : 'Disabled' }}
</el-tag>
</template>
</el-table-column>
</el-table>
<el-pagination
v-model:current-page="page"
v-model:page-size="pageSize"
:total="total"
layout="total, sizes, prev, pager, next"
/>
</el-card>
</template>
💡 The component library manages 'controls': buttons, forms, tables, modals. Theme colors and layout spacing are handled by other layers (Chapter 13). Charts are outside Element Plus's scope (Chapter 11).
4.5 Running Screenshot
Start the dev server:
pnpm dev
📷 Step Screenshot 1: Login Page (redirected by route guard when not logged in)

📷 Step Screenshot 2: Admin Dashboard (logged in, with sidebar menu, theme/language switch buttons)

5. Vue Router: Routing and Lazy Loading
🔗 Corresponding Theory: Chapter 6 (Routing and SPA Skeleton)
src/router/index.ts (excerpt):
import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/views/Layout.vue'
const routes = [
{ path: '/login', name: 'Login', component: () => import('@/views/Login.vue'), meta: { public: true } },
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [
// Dynamic import = lazy loading: the code is downloaded only when this route is visited
{ path: 'dashboard', name: 'Dashboard', component: () => import('@/views/Dashboard.vue') },
{
path: 'users', name: 'Users', component: () => import('@/views/UserManage.vue'),
meta: { permission: 'user:view' }, // permission code, used with Chapter 10
},
{ path: 'chart', name: 'Chart', component: () => import('@/views/ChartPage.vue') },
],
},
]
const router = createRouter({
history: createWebHistory(), // history mode, clean URLs
routes,
})
// Global before guard: redirect to login if not logged in
router.beforeEach((to) => {
const token = localStorage.getItem('app:token')
if (!token && !to.meta.public) return { name: 'Login' }
return true
})
export default router
⚠️ Simplification boundary of this demo: only the 'redirect to login if not logged in' guard is implemented. A real admin system also needs dynamic routing (backend returns menus to generate routes), route-level permission filtering, a 404 fallback, login endpoint / token writing / logout / 401 expiration interception—these are not in the minimal example; the full loop is in theory notes Chapters 6, 10, and 13. Button-level permissions are covered in Chapter 10.
6. Pinia: Global State and Persistence
🔗 Corresponding Theory: Chapters 7 and 10 (Pinia / Login State and Storage)
6.1 Install
pnpm add pinia pinia-plugin-persistedstate
6.2 User Store
src/stores/user.ts:
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { setAccessToken } from '@/api/request'
export const useUserStore = defineStore('user', () => {
// state: defined with ref
const token = ref('')
const name = ref('Guest')
const permissions = ref<string[]>(['user:view'])
// getter: computed, with caching
const isLoggedIn = computed(() => !!token.value)
// permission check method
const hasPermission = (code: string) => permissions.value.includes(code)
// action: the only entry point to modify state
function login(newToken: string, userName: string, codes: string[]) {
token.value = newToken
name.value = userName
permissions.value = codes
setAccessToken(newToken) // sync to the request layer so future requests automatically carry the token
}
function logout() {
token.value = ''
permissions.value = ['user:view']
setAccessToken('')
}
return { token, name, permissions, isLoggedIn, hasPermission, login, logout }
})
6.3 UI Configuration Store (with Persistence)
src/stores/app.ts:
export const useAppStore = defineStore('app', () => {
const theme = ref<'light' | 'dark'>('light')
const locale = ref<'zh-CN' | 'en-US'>('zh-CN')
function toggleTheme() { theme.value = theme.value === 'light' ? 'dark' : 'light' }
function setLocale(l: 'zh-CN' | 'en-US') { locale.value = l }
return { theme, locale, toggleTheme, setLocale }
}, {
persist: { pick: ['theme', 'locale'] }, // persist only these two fields, retained after refresh
})
⚠️ Do not persist the token: that's why the user store doesn't have persist enabled.
The actual practice in this demo: the access token lives only in Pinia memory (synced to the request layer via
setAccessToken), no silent refresh is implemented—refreshing the page requires login again. This keeps the example minimal. Production practice: access token in memory + refresh token in HTTP-only Cookie + silent refresh merged on 401, full sequence in theory notes Chapter 10.
7. Axios: Request Wrapping
🔗 Corresponding Theory: Chapter 9 (HTTP Request Wrapping)
pnpm add axios
src/api/request.ts (the core is three interceptors):
import axios from 'axios'
import { env } from '@/config/env'
// 1. Create instance: environment URL + timeout
const http = axios.create({ baseURL: env.apiBase, timeout: 10000 })
let accessToken = ''
export const setAccessToken = (t: string) => (accessToken = t)
// 2. Request interceptor: unified processing before sending
http.interceptors.request.use((config) => {
if (accessToken) config.headers.Authorization = `Bearer ${accessToken}` // attach token
config.headers['Accept-Language'] = localStorage.getItem('app:locale') ?? 'zh-CN' // attach language
config.headers['X-Trace-Id'] = crypto.randomUUID() // trace ID
if (config.method !== 'get') config.headers['Idempotency-Key'] = crypto.randomUUID() // idempotency key for write requests
return config
})
// 3. Response interceptor: unified unwrap + error handling
http.interceptors.response.use(
(response) => response.data, // directly return data to the caller (note that the type must be adjusted accordingly, see pitfalls)
(error) => {
if (error.response?.status === 401) console.warn('Not logged in, should redirect to login page')
if (error.response?.status === 403) console.warn('Insufficient permissions')
return Promise.reject(error)
},
)
export default http
💡 Idempotency Key: write requests (POST/PUT/DELETE) carry an
Idempotency-Keyto prevent duplicate submissions from repeated clicks. Read requests don't need one.
8. TanStack Query: Server State
🔗 Corresponding Theory: Chapter 8 (Server State and Data Layer)
pnpm add @tanstack/vue-query
8.1 Register the Plugin (Mandatory!)
src/main.ts:
import { VueQueryPlugin } from '@tanstack/vue-query'
app.use(VueQueryPlugin, {
queryClientConfig: { defaultOptions: { queries: { staleTime: 60_000, retry: 1 } } },
})
🔥 Big Pitfall: If you install the dependency but forget
app.use(VueQueryPlugin), the page will render blank and the console will showNo 'queryClient' found in Vue context. This project really hit this, see Chapter 18.
8.2 Use in a Page
src/views/UserManage.vue (excerpt):
import { useQuery } from '@tanstack/vue-query'
// queryKey is a cache identifier: changes in keyword/page trigger a refetch
const queryKey = computed(() => ['users', keyword.value, page.value] as const)
const { isPending, data } = useQuery({
queryKey,
queryFn: () => getUsers({ page: page.value, pageSize: pageSize.value, keyword: keyword.value }),
staleTime: 60_000, // data is considered fresh within 1 minute
})
// Take data from the query result, no need to manually set loading.value = true in the component
const tableData = computed(() => data.value?.list ?? [])
const total = computed(() => data.value?.total ?? 0)
💡 Why it's needed: caching, race conditions (old request overwriting new), invalidation refetch, retries are all handled for you, greatly reducing boilerplate in pages.
A more precise division of responsibilities: TanStack Query focuses on async requests, caching, retries, invalidation refetch, race handling; Pinia is suitable for cross-component client-side interaction state (sidebar expansion, theme, global modals, current user info). The boundary is not a one-size-fits-all 'server data vs client data'—Pinia can also cache minimal server data (common in older projects), and TanStack Query can store business config-like data. The criterion is: do you need to handle async request lifecycle?
Refreshing a list after create/edit (most common in admin systems,
invalidateQueries):
import { useQueryClient } from '@tanstack/vue-query'
const queryClient = useQueryClient()
async function handleCreate() {
await createUser(form) // first write succeeds
await queryClient.invalidateQueries({ queryKey: ['users'] }) // then invalidate the list cache → auto refetch
}
Note the
queryKeyprefix must match (here both are['users', ...]),invalidateQueriesmatches by prefix.
📷 Step Screenshot 3: User Management Page (el-table + search + pagination + data loaded via TanStack Query)

9. i18n: Chinese/English Switching
🔗 Corresponding Theory: Chapters 12 and 38 (Internationalization / Advanced)
pnpm add vue-i18n
src/locales/zh-CN.ts (Chinese pack) and en-US.ts (English pack) use the same key structure:
export default {
menu: { dashboard: '首页', userManage: '用户管理', chart: '数据图表' },
user: { title: '用户列表', name: '姓名', search: '搜索' },
}
src/locales/index.ts:
import { createI18n } from 'vue-i18n'
import zhCN from './zh-CN'
import enUS from './en-US'
export default createI18n({
legacy: false, // use Composition API style
locale: localStorage.getItem('app:locale') ?? 'zh-CN',
fallbackLocale: 'zh-CN', // fallback to Chinese if missing (downgrade)
messages: { 'zh-CN': zhCN, 'en-US': enUS },
})
Usage and switching in a component:
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
function changeLanguage(lang: 'zh-CN' | 'en-US') {
locale.value = lang
localStorage.setItem('app:locale', lang) // remember preference
}
</script>
<template>
<span>{{ t('menu.dashboard') }}</span>
<el-button @click="changeLanguage('en-US')">English</el-button>
</template>
⚠️ Three high-frequency pitfalls:
- Hardcoded Chinese in templates—
<el-button>搜索</el-button>looks fine but won't change when switching to English. All static copy must go throught('xxx'); CI should scan for hardcoded Chinese and block it.$tcan't be used in js/ts—use$t('key')in templates, but in<script setup>you must useconst { t } = useI18n()and thent('key').- Dictionaries/enum values returned by the API—if the backend returns a code like
status: 'active', the frontend should map it to an i18n key (t('status.' + row.status)), or have the backend return the corresponding text based onAccept-Language. In this demo, the status column is hardcoded in Chinese, which is exactly the demonstration of this pitfall; production must fix it.💡 Key points for large projects (simplified in this demo): lazy loading of language packs, key coverage checks, plural / RTL / pseudo-localization. See theory notes Chapters 12 and 38.
10. Permission Directive: Button Show/Hide
🔗 Corresponding Theory: Chapters 13 and 26 (Permission System / Security Specializations)
src/directives/permission.ts:
import type { Directive } from 'vue'
import { useUserStore } from '@/stores/user'
export const permission: Directive<HTMLElement, string | string[]> = {
mounted(el, binding) {
const store = useUserStore()
// binding.value is the required permission code, can be a string or array
const required = Array.isArray(binding.value) ? binding.value : [binding.value]
const allowed = required.some((code) => store.hasPermission(code))
if (!allowed) el.remove() // no permission: remove directly from DOM (safer than display:none)
},
}
Register in src/main.ts:
import { permission } from './directives/permission'
app.directive('permission', permission)
Usage in a page:
<el-button v-permission="'user:delete'" type="danger" link @click="handleDelete(row)">
Delete
</el-button>
Where do permission codes come from: after login, the backend returns the current user's permission code array (e.g.,
['user:view', 'user:delete']), the frontend writes it intouserStore.permissions(thelogin()parameter in Chapter 6), and the directive reads from the store. Don't hardcode role checks in the frontend.⚠️ Security red line: hiding in the frontend is only a UX decision; the backend must authorize every API call. Attackers can call APIs directly bypassing the UI; hiding buttons won't stop them.
⚠️ Simplification boundary of this demo: only button-level
v-permissionis shown; dynamic route filtering, route-level permissions, and horizontal privilege escalation protection are not in the minimal example. In production, you also need to prevent things like 'change the resource ID in the URL to view someone else's order'—the frontend can't do anything about that; the backend must validate each request, see theory notes Chapters 13 and 26.
11. ECharts: Line Chart
🔗 Corresponding Theory: Chapter 15 (Chart Capability ECharts)
pnpm add echarts
11.1 Wrapper Component (business pages only pass configuration)
src/components/global/BaseChart.vue (core logic):
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart, BarChart } from 'echarts/charts' // import chart types on demand
import { GridComponent, TooltipComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([LineChart, BarChart, GridComponent, TooltipComponent, CanvasRenderer]) // register
const props = defineProps<{ option: echarts.EChartsCoreOption; height?: string }>()
const el = ref<HTMLDivElement>()
let chart: echarts.ECharts | undefined
let observer: ResizeObserver | undefined
function render() {
if (!el.value) return
if (!chart) chart = echarts.init(el.value) // initialize only once
chart.setOption(props.option)
}
onMounted(() => {
render()
observer = new ResizeObserver(() => chart?.resize()) // adapt to container changes
if (el.value) observer.observe(el.value)
})
watch(() => props.option, render, { deep: true }) // redraw when config changes
onBeforeUnmount(() => {
observer?.disconnect()
chart?.dispose() // ⚠️ key: must destroy on unmount, otherwise memory leak
chart = undefined
})
</script>
<template>
<div ref="el" :style="{ width: '100%', height: height ?? '300px' }" />
</template>
11.2 Usage in a Business Page
<BaseChart :option="option" height="360px" />
const option = ref({
tooltip: { trigger: 'axis' },
xAxis: { type: 'category', data: ['Jan', 'Feb', 'Mar'] },
yAxis: { type: 'value' },
series: [{ type: 'line', smooth: true, data: [120, 200, 150] }],
})
📷 Step Screenshot 4: Line Chart Page (ECharts line chart renders correctly)

12. Day.js: Time Utilities
🔗 Corresponding Theory: Chapter 16 (Date and Time Handling)
pnpm add dayjs
src/utils/time.ts:
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime' // relative time plugin
import utc from 'dayjs/plugin/utc' // timezone plugin
dayjs.extend(relativeTime)
dayjs.extend(utc)
// Table display format
export const formatDateTime = (v: string | number | Date) => dayjs(v).format('YYYY-MM-DD HH:mm:ss')
// Send to backend: UTC ISO with Z (unambiguous timestamp, no timezone ambiguity)
export const toUtcISO = (v: string | number | Date) => dayjs(v).utc().format('YYYY-MM-DDTHH:mm:ss[Z]')
// Relative time: "3 minutes ago"
export const fromNow = (v: string | number | Date) => dayjs(v).fromNow()
// Pure date (birthday, accounting period): no time, no timezone conversion
export const formatDate = (v: string | number | Date) => dayjs(v).format('YYYY-MM-DD')
⚠️ Timezone discipline: timestamps sent to the backend must include timezone (ISO
Zor millisecond timestamp); never send a string like2026-11-25 10:00:00without timezone. Pure dates useYYYY-MM-DD.
13. CSS Variables: Theme Switching
🔗 Corresponding Theory: Chapter 17 (Theme Switching)
src/styles/theme.css — the single source of truth for colors:
/* Light theme: defined on the root :root */
:root {
--color-primary: #409eff;
--bg-base: #f5f7fa;
--bg-secondary: #ffffff;
--text-primary: #303133;
--border-color: #e4e7ed;
}
/* Dark theme: overrides the above values when html has .dark class */
html.dark {
--color-primary: #79bbff;
--bg-base: #1d1e1f;
--bg-secondary: #252526;
--text-primary: #e5e5e5;
--border-color: #414243;
color-scheme: dark;
}
body {
margin: 0;
background: var(--bg-base); /* use variables, don't hardcode colors */
color: var(--text-primary);
}
In src/views/Layout.vue, switch the theme:
import { watch } from 'vue'
import { useAppStore } from '@/stores/app'
const appStore = useAppStore()
// Watch theme changes, add/remove dark class on html, CSS variables switch automatically
watch(() => appStore.theme,
(theme) => document.documentElement.classList.toggle('dark', theme === 'dark'),
{ immediate: true }) // immediate: run once on entry to prevent theme not applied after refresh
Never hardcode colors in business code; always use var(--color-primary) and similar.
⚠️ Coordination with Element Plus dark mode: Element Plus has its own dark scheme—when
html.darkis set, it uses its own set of dark variables. If you write a custom set of colors underhtml.dark, it can conflict with the component library's built-in styles (e.g., input background is yours, text is theirs). Prefer the official solution: importelement-plus/theme-chalk/dark/css-vars.css, and then in thehtml.darkscope only override the custom variables you need (like--el-color-primary), don't reinvent the whole color scheme.💡 Persistence is complete:
appStorehaspersist: { pick: ['theme'] }(Chapter 6), and thewatchabove hasimmediate: true, so on page refresh it reads the persisted value first and then sets thehtml.darkclass, preventing a flash of light theme.
📷 Step Screenshot 5: Dark Mode (the whole site darkens after switching, CSS variables take effect)

💡 Why not use SCSS variables for theming: SCSS is compile-time; after bundling, colors are hardcoded and can't be changed at runtime. CSS variables are runtime; changing a class in JS can switch themes. SCSS is only suitable for structural organization like nesting/mixins.
14. Mock: Fake Data
🔗 Corresponding Theory: Chapter 18 (Mock and Frontend-Backend Contracts)
When the backend API isn't ready, use fake data to get the frontend running.
src/mock/data.ts:
import type { User, PageResult, PageParams } from '@/types/api'
// Create 12 fake users
const USERS: User[] = Array.from({ length: 12 }, (_, i) => ({
id: i + 1,
name: `User ${i + 1}`,
email: `user${i + 1}@example.com`,
status: i % 4 === 0 ? 'disabled' : 'active',
role: i === 0 ? 'admin' : 'viewer',
}))
// Simulate a paginated query: used as a fallback when the real API fails
export function mockGetUsers(params: PageParams): PageResult<User> {
const start = (params.page - 1) * params.pageSize
return { list: USERS.slice(start, start + params.pageSize), total: USERS.length }
}
Fallback in src/api/user.ts:
export async function getUsers(params: PageParams) {
try {
const res = await request.get('/users', { params })
if (res?.data) return res.data // use real data if the real API returns data
} catch { /* API is down, fall back to mock */ }
return mockGetUsers(params) // fallback: fake data keeps the page demonstrable
}
⚠️ Anti-pattern warning: the above approach of an
iffallback mock inapi/user.tsis only suitable for a minimal demo—mock code gets bundled into the production package and is mixed into business request functions, requiring manual removal or a switch before release, which is prone to accidents.Production approach: two options ① Use environment variables to control whether to import the mock module (only load under
import.meta.env.DEV); ② Use MSW to intercept requests at the service worker layer in development, and never register it in production. When the real API isn't ready, prefer option ②, as both development and testing can reuse it, see theory notes Chapter 18.
15. Testing: Vitest Unit Tests
🔗 Corresponding Theory: Chapter 21 (Testing System)
pnpm add -D vitest
src/utils/time.test.ts:
import { describe, it, expect } from 'vitest'
import { formatDate, toUtcISO } from './time'
describe('time utility functions', () => {
it('formats pure dates without timezone conversion', () => {
expect(formatDate('2026-11-25T10:00:00')).toBe('2026-11-25')
})
it('converts to UTC ISO with Z indicator', () => {
const iso = toUtcISO('2026-11-25T10:00:00')
expect(iso).toContain('Z') // key: must have Z, otherwise backend parsing fails
})
})
pnpm test
Output:
✓ src/utils/time.test.ts (2 tests)
Test Files 1 passed (1)
Tests 2 passed (2)
💡 Testing scope boundary: this project only writes unit tests for core utility functions and pure logic (time formatting, permission checks, validation rules), which gives the highest return on investment. Business pages are not forced to have component tests—using
@vue/test-utilsto test pages requires mocking routes, stores, and APIs, and the maintenance cost often exceeds the benefit; if you do test components, prioritize common reusable components (likeBaseChart) instead of business pages. Integration / end-to-end scenarios go to E2E (Playwright) + visual regression, see theory notes Chapter 21.
16. Commit Validation: Git Hooks
🔗 Corresponding Theory: Chapters 2 and 22 (Commit Constraints / CI/CD)
pnpm add -D simple-git-hooks
package.json configuration (auto-run lint and type check before commits):
"scripts": {
"prepare": "simple-git-hooks"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint && pnpm typecheck"
}
# Install hooks
pnpm install
After this, every git commit will first run lint + type check, and block the commit if they fail.
⚠️ Large projects should change to only check files in the current commit: the
pre-commit: "pnpm lint && pnpm typecheck"above is a full project scan, which becomes slow as files grow. For production, switch tolint-stagedto only run on the staging area:
pnpm add -D lint-staged
"simple-git-hooks": { "pre-commit": "pnpm lint-staged" },
"lint-staged": {
"*.{ts,vue}": ["eslint --fix", "prettier --write"]
}
prettier --writedirectly appends the formatting results to the current commit, avoiding 'formatted but not staged'. Type checking (tsc) is global and not suitable for lint-staged; it's better to put it in a CI pipeline. See theory notes Chapters 2 and 22.
17. Build and Verification Command Quick Reference
🔗 Corresponding Theory: Comprehensive (Chapters 19-22 Engineering)
The full command sequence to run the project (copy-paste ready):
cd E:\ai_work\06_learning_demo\demo
pnpm install # Install dependencies
pnpm dev # Dev server http://localhost:5173
pnpm build # Type check + production bundle
pnpm preview # Preview production build
pnpm lint # ESLint check
pnpm lint:fix # ESLint auto-fix
pnpm format # Prettier format
pnpm typecheck # Type check only
pnpm test # Run unit tests
Final verification results (all green in this project):
pnpm lint ✓ no errors
pnpm typecheck ✓ passed
pnpm test ✓ 2 tests passed
pnpm build ✓ built in ~6s
18. Pitfall Log (Real Issues Encountered and Fixed)
🔗 Corresponding Theory: Various chapters correspond to the 'Common Pitfalls' sections in theory notes
These are not fabricated; they were real errors encountered during hands-on practice and fixed. They are recorded to help readers avoid them. Grouped by troubleshooting scenario, sorted by how hidden they are: Pitfalls 6 and 9 are the most hidden, read them first.
| Category | Pitfall |
|---|---|
| Dependencies and Installation | Pitfall 1 (pnpm 12 blocks scripts) |
| Configuration and Types | Pitfall 2 (missing comma), Pitfall 3 (alias TS doesn't recognize), Pitfall 4 (baseUrl deprecated), Pitfall 5 (Vue+TS parser) |
| Runtime and White Screen | Pitfall 6 (forgot VueQuery)🔥, Pitfall 7 (Query data undefined) |
| Toolchain and Screenshot Specifics | Pitfall 9 (screenshot pollutes lint)🔥, Pitfall 8 (headless white screen, only for custom script, unrelated to framework) |
Pitfall 1: pnpm 12 Blocks Install Scripts
Symptom: pnpm add reports ERR_PNPM_IGNORED_BUILDS, saying Ignored build scripts: vue-demi, simple-git-hooks.
Cause: pnpm 12 strengthens supply chain security and does not execute dependency install scripts by default.
Solution:
pnpm approve-builds --all # approve these packages to run build scripts
After approval, it generates pnpm-workspace.yaml:
allowBuilds:
simple-git-hooks: true
vue-demi: true
💡 Note: pnpm 12 no longer reads the
pnpm.onlyBuiltDependenciesfield inpackage.json; it must be written in this yaml.
Pitfall 2: Missing Comma in package.json
Symptom: pnpm build throws expected ',' or '}' at line 20.
Cause: after editing the simple-git-hooks configuration block, forgot to add a comma after the closing brace.
Solution: fields in a JSON object must be separated by commas; check adjacent configuration blocks.
Pitfall 3: TypeScript Doesn't Recognize the @ Alias
Symptom: Cannot find module '@/config/env'.
Cause: the alias is only configured in vite.config.ts, not in tsconfig.app.json.
Solution: configure it in both places (see Chapter 3).
Pitfall 4: TypeScript 6 Deprecates baseUrl
Symptom: Option 'baseUrl' is deprecated.
Solution: remove baseUrl and write paths directly as "@/*": ["./src/*"].
Pitfall 5: ESLint Can't Parse TypeScript in Vue
Symptom: syntax in <script setup lang="ts"> reports Parsing error: Unexpected token.
Cause: vue.configs['flat/recommended'] uses the default parser.
Solution: add an extra block specifying vue-eslint-parser with parserOptions.parser = tseslint.parser (see Chapter 2).
Pitfall 6: Forgot to Register VueQueryPlugin causing White Screen 🔥
Symptom: user management page is blank, console shows No 'queryClient' found in Vue context.
Cause: installed @tanstack/vue-query but forgot app.use(VueQueryPlugin) in main.ts.
Solution: register the plugin in main.ts (see Chapter 8). This is the most hidden pitfall—a successful install doesn't mean it's usable.
Pitfall 7: Query data cannot be undefined
Symptom: table shows No Data, console shows Query data cannot be undefined.
Cause: the demo backend doesn't exist, axios request returns HTML, res.data is undefined.
Solution: add a guard in the queryFn—fallback to mock data when res?.data doesn't exist, never return undefined (see Chapter 14).
💡 Another common cause: the queryFn throws an exception but it's caught and
return undefined; Query will also report this error. The correct approach is to throw the exception on error (so Query enters the error state) and handle it withonErroror error boundaries; never silently return undefined.
Pitfall 8: Headless Screenshot Blank (Custom Screenshot Script Specific, Unrelated to the Framework)
This is about the screenshot script I wrote for the notes, not a pitfall of the frontend scaffold itself. Readers who don't write screenshot scripts can skip it.
Symptom: Chrome headless screenshot is white.
Cause: captured too early, Vue hasn't rendered yet; or Vite's dependency pre-bundling triggers a page reload.
Solution: use CDP's Page.addScriptToEvaluateOnNewDocument to pre-inject the token + wait 3-5 seconds + pre-warm all routes before capturing. The script is in screenshots/shot2.mjs.
Pitfall 9: Lint Reports Tens of Thousands of Errors after Screenshots 🔥
Symptom: after capturing screenshots, pnpm lint reports 37277 problems, all from unreadable Chrome extension JS files.
Cause: when using Chrome headless for screenshots, --user-data-dir pointed to the screenshots/ directory inside the project, generating hidden directories like .chrome-profile and .profile2 containing many extension JS files. ESLint recursively scans hidden directories.
Solution: add the screenshot directory to the ignores in eslint.config.js:
ignores: [
'dist/**', 'node_modules/**',
'screenshots/**', // screenshot and screenshot script directories are not checked
]
💡 General principle: always exclude screenshot / CI artifacts / temporary file directories from the lint scope, otherwise they'll pollute check results.
19. What Else Can Be Added
🔗 Corresponding Theory: Chapters 19-39 (Engineering / Security / Advanced)
This project already introduces common capabilities 'comprehensively but not deeply'. The theoretical notes mention these additional directions; when needed, add a minimal example the same way. Items marked ⭐ high-frequency for admin systems should be prioritized—most admin systems will need them eventually.
| Direction | Dependencies/capabilities needed when required |
|---|---|
| ⭐ Bundle size analysis | rollup-plugin-visualizer, generates analysis report after build, with the size budget gate from theory Chapter 19 |
| ⭐ Deploy under subpath | base: '/admin/' in vite.config.ts, prefix for static asset paths, high-frequency for admin deployment |
| ⭐ Environment variable type hints | src/env.d.ts (already added in Chapter 4) |
| Upload and preview | Element Plus Upload + object storage + pdfjs |
| Rich text / Markdown | Tiptap + DOMPurify (prevent XSS) |
| WebSocket/SSE real-time messages | native EventSource or WebSocket |
| Excel import/export | SheetJS + Web Worker |
| Micro frontend | qiankun or Module Federation |
| Error boundaries and monitoring | Sentry + Vue onErrorCaptured |
| CI/CD | GitHub Actions / GitLab CI pipeline |
| Virtual list | vue-virtual-scroller |
| Unit testing expansion | Playwright E2E + visual regression |
Keep the principle: add only when you hit a real need, don't prepile. For each addition, write a hands-on guide like this one with screenshots.
Screenshot script explanation (readers who just want to run the project can skip): the 5 screenshots in this book were generated by screenshots/shot2.mjs, using the system Chrome headless + CDP (Node 22 built-in WebSocket), no need to install Playwright:
# First ensure the dev server is running, then run the screenshot script
pnpm dev # terminal 1
node screenshots/shot2.mjs # terminal 2, output goes to screenshots/
Note two points: after
pnpm dev, do not append| head(the pipe will cause SIGPIPE and exit the server early); if Chrome processes remain after screenshots, usetaskkill /F /IM chrome.exeto clean up (see Pitfall 8, Pitfall 9).
(To be continued—if you need practical steps in a specific direction, keep writing.)