Dark mode
Core Concepts
Concept | Description | Key Features |
---|---|---|
Nitro Engine | เซิร์ฟเวอร์เอนจินสำหรับ Nuxt | SSR/API routes, ไฟล์ server/ , โหมด Hybrid rendering |
Vite | เครื่องมือ build หลัก | Hot Module Replacement, Build เร็ว, Plugin ecosystem |
Composition API | รูปแบบการเขียน Vue components | setup() function, ref() /reactive() , Composables |
Nuxt Layers | การแชร์และการขยาย configuration | Extend projects, Share components, Unified config |
Auto-imports | การนำเข้าอัตโนมัติ | Components, Composables, Vue APIs |
File-based Routing | ระบบ routing จากโครงสร้างไฟล์ | pages/ directory, Dynamic routes, Route middleware |
Key Features
คุณสมบัติ | รายละเอียด | ตัวอย่าง |
---|---|---|
File-based Routing | สร้างเส้นทางอัตโนมัติจากโครงสร้างไฟล์ | pages/about.vue → /about |
Server-side Rendering | การแสดงผลฝั่งเซิร์ฟเวอร์ | ใช้ useAsyncData() สำหรับดึงข้อมูลใน SSR |
Static Site Generation | การสร้างเว็บไซต์แบบสแตติก | คำสั่ง nuxi generate |
Auto Imports | นำเข้า components/composables อัตโนมัติ | ใช้ useFetch() โดยไม่ต้อง import |
Modules System | ระบบโมดูลสำหรับเพิ่มความสามารถ | @nuxt/image , @nuxt/content |
Hybrid Rendering | ผสมผสาน SSR, SSG และ CSR ในแอปเดียว | definePageMeta({ static: true }) |
DevTools | เครื่องมือพัฒนาที่มีในตัว | เข้าถึงที่ http://localhost:3000/__nuxt |
API Routes | สร้าง API endpoints ฝั่งเซิร์ฟเวอร์ | ไฟล์ใน server/api/ จะกลายเป็นเส้นทาง API |
Middleware | การจัดการความปลอดภัยของเส้นทาง | definePageMeta({ middleware: 'auth' }) |
State Management | การจัดการสถานะที่มีในตัว | const count = useState('counter', () => 0) |
Getting Started
- Installation
ติดตั้ง Nuxt.js และ dependencies ที่จำเป็นด้วย package manager ที่คุณเลือก:
bash
npm install
npm run dev
bash
pnpm install
pnpm run dev
bash
yarn install
yarn dev
bash
bun install
bun run dev
- Run Development Server
เริ่มต้น development server สำหรับการพัฒนาแบบ real-time:
bash
npm run dev
- Build for Production
สร้างไฟล์สำหรับ production ที่ optimize แล้ว:
bash
npm run build
Directory Structure
โครงสร้างไดเรกทอรีมาตรฐานของ Nuxt:
components/
: เก็บ UI components ที่นำกลับมาใช้ได้pages/
: สร้าง routes อัตโนมัติจากไฟล์server/
: เก็บ API endpoints และ server logiccomposables/
: เก็บ reusable composables- แต่ละโฟลเดอร์มีหน้าที่เฉพาะเจาะจง
my-nuxt-app/
├── .nuxt/ # Generated files (auto-generated, don't modify)
│ ├── dist/ # Production build files
│ └── nitro/ # Server build files
├── assets/ # Static assets
│ ├── css/main.css # Global CSS
│ └── images/logo.png # Site logo
├── components/ # Reusable Vue components
│ ├── AppHeader.vue # Main navigation
│ └── AppFooter.vue # Site footer
├── composables/ # Composable functions
│ └── useFetchData.ts # Data fetching logic
├── layouts/ # Layout components
│ └── default.vue # Default page layout
├── pages/ # Auto-routed pages
│ ├── index.vue # Home page
│ ├── about.vue # About page
│ └── products/[id].vue # Dynamic product page
├── public/ # Directly served static files
│ └── favicon.ico # Site favicon
├── server/ # Server handlers and API routes
│ ├── api/hello.ts # API endpoint
│ └── middleware/ # Server middleware
└── nuxt.config.ts # Nuxt configuration file
Rendering
Rendering Modes Comparison
Mode | SEO | Performance | Use Case | Config |
---|---|---|---|---|
SSR (Universal) | ดีเยี่ยม | โหลดเร็วครั้งแรก | เว็บเนื้อหา | ssr: true |
SSG (Static) | ดีเยี่ยม | เร็วมาก | บล็อก, เอกสาร | npm run generate |
CSR (Client) | ต่ำ | โหลดช้าครั้งแรก | แดชบอร์ด | ssr: false |
Hybrid | ดี | สมดุล | เนื้อหาผสม | กำหนดค่าแต่ละหน้า |
Configuration Examples
ts
// nuxt.config.ts
export default defineNuxtConfig({
ssr: true,
nitro: {
preset: 'node-server'
}
})
ts
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'static'
}
})
ts
// pages/products/[id].vue
definePageMeta({
static: true // Pre-render this page
})
Rendering Modes
Nuxt supports multiple rendering modes:
Mode | Description | Command |
---|---|---|
Universal (SSR) | Server-side rendering | npm run build |
Static (SSG) | Pre-rendered static site | npm run generate |
Client-side | SPA mode only | ssr: false in nuxt.config |
Hybrid | Mix of SSR and SSG | definePageMeta({ static: true }) |
Switching Modes
Configure in nuxt.config.ts
:
ts
export default defineNuxtConfig({
ssr: true, // Enable SSR
nitro: {
preset: 'node-server' // or 'static'
}
})
Server
Feature | Description | Location |
---|---|---|
API Routes | จุดเชื่อมต่อ API บนเซิร์ฟเวอร์ | server/api/ |
Middleware | ตัวกรองการร้องขอ API | server/middleware/ |
Plugins | ส่วนขยายเซิร์ฟเวอร์ | server/plugins/ |
Nitro | เครื่องมือเซิร์ฟเวอร์ของ Nuxt | nuxt.config.ts |
ts
// server/api/hello.ts
export default defineEventHandler((event) => {
return { message: 'Hello World' }
})
ts
// server/middleware/auth.ts
export default defineEventHandler((event) => {
// Authentication logic
})
ts
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'node-server'
}
})
Middleware
Middleware ใน Nuxt มี 2 ประเภทหลัก:
- Route middleware: ตรวจสอบก่อนเข้าหน้าเว็บ
- Server middleware: ตรวจสอบ request ก่อนถึง API
- สามารถสร้างเป็นไฟล์
.ts
ในโฟลเดอร์ที่เกี่ยวข้อง - ใช้
defineNuxtRouteMiddleware
หรือdefineEventHandler
Type | Location | Description |
---|---|---|
Route | middleware/ | ตัวกรองการนำทางระหว่างหน้า |
Server | server/middleware/ | ตัวกรองการร้องขอ API |
Named | definePageMeta | ตัวกรองเฉพาะหน้า |
ts
// middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {
if (!isAuthenticated()) {
return navigateTo('/login')
}
})
ts
// server/middleware/log.ts
export default defineEventHandler((event) => {
console.log('Request:', event.path)
})
vue
<script setup>
definePageMeta({
middleware: ['auth']
})
</script>
Pages and Routing
Nuxt สร้างเส้นทางอัตโนมัติจากโครงสร้างไดเรกทอรี pages/
Concept | Description | Example |
---|---|---|
Basic Route | เส้นทางพื้นฐานจากไฟล์ | pages/index.vue → / |
Dynamic Route | เส้นทางแบบไดนามิกด้วยพารามิเตอร์ | pages/users/[id].vue → /users/123 |
Nested Route | เส้นทางแบบซ้อนจากโฟลเดอร์ | pages/products/index.vue → /products |
vue
<!-- pages/index.vue -->
<template>
<div>Home Page</div>
</template>
vue
<!-- pages/users/[id].vue -->
<template>
<div>User ID: {{ $route.params.id }}</div>
</template>
vue
<!-- pages/about.vue -->
<template>
<div>หน้าเกี่ยวกับเรา</div>
</template>
Layer
คุณสมบัติ | คำอธิบาย | การกำหนดค่า |
---|---|---|
Extends | แชร์ components/config | nuxt.config.ts |
Presets | การตั้งค่าล่วงหน้า | extends: ['@nuxt/ui'] |
Modules | เพิ่มความสามารถ | modules: [] |
ts
// nuxt.config.ts
export default defineNuxtConfig({
extends: ['github:owner/repo']
})
ts
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxt/image']
})
ts
// my-layer/nuxt.config.ts
export default defineNuxtConfig({
components: {
dirs: ['~/components']
}
})
View
คุณสมบัติ | คำอธิบาย | ตัวอย่าง |
---|---|---|
Templates | โครงสร้างเลย์เอาต์ | layouts/default.vue |
Components | องค์ประกอบ UI ที่นำกลับมาใช้ใหม่ได้ | components/ |
Pages | องค์ประกอบเส้นทาง | pages/ |
Dynamic Imports | การโหลดแบบล่าช้า | defineAsyncComponent |
vue
<!-- layouts/default.vue -->
<template>
<div>
<AppHeader />
<slot />
<AppFooter />
</div>
</template>
vue
<script setup>
const Component = defineAsyncComponent(
() => import('@/components/HeavyComponent.vue')
)
</script>
<template>
<Component />
</template>
ts
// nuxt.config.ts
export default defineNuxtConfig({
app: {
pageTransition: { name: 'page', mode: 'out-in' }
}
})
Styling
Method | Description | Configuration |
---|---|---|
UnoCSS | ระบบ Atomic CSS | uno.config.ts |
SCSS | ภาษา CSS ขั้นสูง | npm install -D sass |
CSS Modules | สไตล์แบบเฉพาะที่ | *.module.css |
ts
// uno.config.ts
export default defineConfig({
presets: [presetUno(), presetIcons()]
})
vue
<style lang="scss">
$primary: #00dc82;
.button {
background: $primary;
}
</style>
vue
<template>
<div :class="$style.container">Content</div>
</template>
<style module>
.container { color: var(--primary) }
</style>
SEO and Meta
Nuxt มี utilities สำหรับจัดการ SEO และ meta tags:
useHead
: สำหรับตั้งค่า meta tags พื้นฐานuseSeoMeta
: สำหรับ meta tags ของโซเชียลมีเดีย@nuxtjs/sitemap
: สร้าง sitemap.xml อัตโนมัติ- Meta tags จะถูก inject ใน SSR/SSG mode
เทคนิค | คำอธิบาย | การใช้งาน |
---|---|---|
Basic Meta | เมตาแท็กพื้นฐาน | SEO ทั่วไป |
Social Meta | OpenGraph/Twitter cards | การแชร์บนโซเชียล |
Sitemap | การสร้างแผนผังเว็บไซต์ | การจัดทำดัชนีโดยเสิร์ชเอนจิน |
vue
<script setup>
useHead({
title: 'หน้าแรก',
meta: [
{ name: 'description', content: 'คำอธิบายเว็บไซต์' },
{ name: 'keywords', content: 'nuxt, vue, javascript' }
]
})
</script>
vue
<script setup>
useSeoMeta({
title: 'หน้าแรก',
ogTitle: 'หน้าแรก | เว็บไซต์ของฉัน',
ogDescription: 'คำอธิบายเว็บไซต์สำหรับ social media',
ogImage: 'https://example.com/image.jpg'
})
</script>
ts
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxtjs/sitemap'],
sitemap: {
hostname: 'https://example.com',
routes: ['/', '/about']
}
})
Data Fetching
วิธี | คำอธิบาย | เหมาะสำหรับ |
---|---|---|
useFetch | คอมโพเซเบิลที่นำเข้าโดยอัตโนมัติ | การร้องขอฝั่งไคลเอนต์ |
useAsyncData | การดึงข้อมูลที่เข้ากันได้กับ SSR | การเรนเดอร์แบบสากล |
$fetch | ไคลเอนต์ HTTP โดยตรง | การเรียก API แบบแมนนวล |
vue
<script setup>
const { data: posts } = await useFetch('/api/posts')
</script>
vue
<script setup>
const { data: user } = await useAsyncData('user', () =>
$fetch('/api/user')
)
</script>
ts
// server/api/posts.ts
export default defineEventHandler(async () => {
return await database.query('SELECT * FROM posts')
})
State Management
การจัดการสถานะใน Nuxt มีหลายวิธี:
useState
: สำหรับสถานะระดับ component- Pinia: สำหรับสถานะ global
- Shared State: สำหรับสถานะที่แชร์ระหว่าง components
- สามารถใช้ร่วมกับ server-side rendering ได้
วิธี | คำอธิบาย | เมื่อไหร่ควรใช้ |
---|---|---|
useState | สถานะ reactive ในตัว | สถานะ component อย่างง่าย |
Pinia | การจัดการสถานะอย่างเป็นทางการ | แอปพลิเคชันที่ซับซ้อน |
Shared State | สถานะ reactive แบบ global | สถานะข้าม component |
ts
// composables/useCounter.ts
export const useCounter = () => {
return useState('counter', () => 0)
}
ts
// stores/counter.ts
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() { this.count++ }
}
})
ts
// composables/useSharedState.ts
export const useSharedState = () => {
return useState('shared', () => ({
user: null,
theme: 'light'
}))
}
Deployment
เป้าหมาย | คำสั่ง | การกำหนดค่า |
---|---|---|
Node Server | nuxt build | nitro.preset: 'node-server' |
Static Hosting | nuxt generate | nitro.preset: 'static' |
Edge Functions | nuxt build | nitro.preset: 'vercel-edge' |
Docker | docker build | Dockerfile |
bash
npm run generate
dockerfile
FROM node:18
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
CMD ["npm", "run", "start"]
ts
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'vercel'
}
})
Optimizing
เทคนิค | คำอธิบาย | การนำไปใช้ |
---|---|---|
Lazy Loading | โหลดคอมโพเนนต์เมื่อต้องการ | defineAsyncComponent |
Image Optimization | การประมวลผลภาพอัตโนมัติ | @nuxt/image |
Code Splitting | แยกบันเดิลโดยอัตโนมัติ | Built-in |
Compression | การบีบอัด Gzip/Brotli | nitro.compressPublicAssets |
ts
const Component = defineAsyncComponent(
() => import('@/components/HeavyComponent.vue')
)
ts
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxt/image'],
image: {
provider: 'ipx'
}
})
Environment Variables
การจัดการ environment variables ใน Nuxt:
- ตัวแปรสาธารณะ (public): เข้าถึงได้ทั้งฝั่ง client และ server
- ตัวแปรส่วนตัว (private): เข้าถึงได้เฉพาะฝั่ง server
- runtimeConfig: สำหรับการกำหนดค่าที่สามารถ override ได้
- ควรเก็บค่าลับในไฟล์
.env
ที่ไม่ถูก commit
ประเภทตัวแปร | การใช้งาน | ตัวอย่าง |
---|---|---|
Public | เข้าถึงได้ฝั่งไคลเอนต์ | NUXT_PUBLIC_API_BASE |
Private | เฉพาะฝั่งเซิร์ฟเวอร์ | DATABASE_URL |
Runtime Config | การเข้าถึงแบบ type-safe | runtimeConfig |
sh
# Public (client-side)
NUXT_PUBLIC_API_BASE=https://api.example.com
# Private (server-only)
DATABASE_URL=postgres://user:pass@localhost:5432/db
ts
// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
apiSecret: '', // Can be overridden by NUXT_API_SECRET
public: {
apiBase: '/api' // NUXT_PUBLIC_API_BASE
}
}
})
vue
<script setup>
const config = useRuntimeConfig()
// Client-side
const apiBase = config.public.apiBase
// Server-side (API routes)
// const apiSecret = config.apiSecret
</script>
## Best Practices
| Category | Recommendation | Implementation |
|----------|----------------|----------------|
| Composables | ใช้คอมโพเซเบิลที่นำเข้าโดยอัตโนมัติ | `useFetch`, `useAsyncData` |
| Structure | ใช้โครงสร้างไดเรกทอรีมาตรฐาน | `components/`, `composables/` |
| Type Safety | ใช้ TypeScript | `tsconfig.json` |
| Modules | ใช้โมดูล Nuxt | `modules: []` |
| Configuration | ใช้ไฟล์กำหนดค่า | `nuxt.config.ts` |
::: code-group
```ts [Composables Example]
<script setup>
const { data } = await useAsyncData('users', () => {
return $fetch('/api/users')
})
</script>
ts
// โครงสร้างมาตรฐาน
components/
AppHeader.vue
composables/
useAuth.ts
pages/
index.vue
ts
// tsconfig.json
{
"compilerOptions": {
"strict": true
}
}