# Tham Khảo Nhanh Vue.js

*Templates, reactivity, components, Composition API, router*

> Source: Vue.js Documentation (vuejs.org) · MIT

## Cú pháp Template

### Văn bản & Biểu thức

```
<span>{{ message }}</span>
<span>{{ count + 1 }}</span>
<span>{{ ok ? 'Yes' : 'No' }}</span>
<span v-html="rawHtml"></span>
```

### Directives

| Command | Description |
|---------|-------------|
| `{{ expr }}` | Nội suy văn bản |
| `v-bind:attr / :attr` | Gắn thuộc tính vào biểu thức |
| `v-on:event / @event` | Gắn trình lắng nghe sự kiện |
| `v-model` | Binding hai chiều (form) |
| `v-if / v-else-if / v-else` | Render có điều kiện |
| `v-show` | Bật/tắt display CSS (vẫn giữ trong DOM) |
| `v-for` | Render danh sách |
| `v-slot / #name` | Nội dung slot có tên |

### Binding thuộc tính

```
<img :src="imageUrl" :alt="desc" />
<div :class="{ active: isActive }"></div>
<div :style="{ color: textColor }"></div>
<button :disabled="isLoading">Submit</button>
```

## Reactivity

### ref (giá trị nguyên thủy)

```
import { ref } from 'vue'

const count = ref(0)
console.log(count.value)  // 0
count.value++             // reactive update
```

### reactive (đối tượng)

```
import { reactive } from 'vue'

const state = reactive({ count: 0, name: 'Vue' })
state.count++  // no .value needed
```

### ref vs reactive

| Command | Description |
|---------|-------------|
| `ref()` | Mọi kiểu; truy cập bằng `.value` trong script |
| `reactive()` | Chỉ object/array; truy cập thuộc tính trực tiếp |
| `Template` | Cả hai tự động unwrap (không cần `.value`) |
| `Destructure` | `reactive` mất reactivity khi destructure; dùng `toRefs()` |

## Computed & Watchers

### Computed

```
import { ref, computed } from 'vue'

const items = ref([1, 2, 3, 4, 5])
const evenItems = computed(() =>
  items.value.filter(n => n % 2 === 0)
)
```

*Giá trị computed được cache, chỉ tính lại khi dependency thay đổi*

### Watchers

```
import { ref, watch, watchEffect } from 'vue'

const query = ref('')

// Watch specific source
watch(query, (newVal, oldVal) => {
  console.log(`Changed: ${oldVal} → ${newVal}`)
})

// Auto-track dependencies
watchEffect(() => {
  console.log(`Query is: ${query.value}`)
})
```

### Tùy chọn Watch

| Command | Description |
|---------|-------------|
| `immediate: true` | Chạy callback ngay khi tạo |
| `deep: true` | Theo dõi sâu đối tượng lồng nhau |
| `flush: 'post'` | Chạy sau khi DOM cập nhật |
| `once: true` | Chỉ kích hoạt một lần rồi dừng |

## Components

### Single File Component (SFC)

```
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>

<template>
  <button @click="count++">{{ count }}</button>
</template>

<style scoped>
button { font-size: 1.2em; }
</style>
```

### Đăng ký Component

```
<!-- Auto-imported with <script setup> -->
<script setup>
import MyButton from './MyButton.vue'
</script>

<template>
  <MyButton label="Click me" />
</template>
```

### Các khối SFC

| Command | Description |
|---------|-------------|
| `<script setup>` | Composition API (khuyến nghị) |
| `<template>` | Template HTML |
| `<style scoped>` | CSS theo phạm vi component |
| `<style module>` | CSS module (đối tượng $style) |

## Props & Events

### Định nghĩa Props

```
<script setup>
const props = defineProps({
  title: String,
  count: { type: Number, default: 0 },
  items: { type: Array, required: true }
})
</script>
```

### Emit Events

```
<script setup>
const emit = defineEmits(['update', 'delete'])

function handleClick() {
  emit('update', { id: 1, value: 'new' })
}
</script>
```

### Dùng trong component cha

```
<ChildComponent
  :title="pageTitle"
  :count="total"
  @update="handleUpdate"
  @delete="handleDelete"
/>
```

### v-model trong Component

```
<!-- Parent -->
<CustomInput v-model="search" />

<!-- CustomInput.vue -->
<script setup>
const model = defineModel()
</script>
<template>
  <input :value="model" @input="model = $event.target.value" />
</template>
```

## Slots

### Slot mặc định

```
<!-- Card.vue -->
<template>
  <div class="card">
    <slot>Fallback content</slot>
  </div>
</template>

<!-- Usage -->
<Card><p>Custom content here</p></Card>
```

### Slot có tên

```
<!-- Layout.vue -->
<template>
  <header><slot name="header" /></header>
  <main><slot /></main>
  <footer><slot name="footer" /></footer>
</template>

<!-- Usage -->
<Layout>
  <template #header><h1>Title</h1></template>
  <p>Main content</p>
  <template #footer><span>Footer</span></template>
</Layout>
```

### Scoped Slots

```
<!-- List.vue -->
<ul>
  <li v-for="item in items" :key="item.id">
    <slot :item="item" />
  </li>
</ul>

<!-- Usage -->
<List :items="todos">
  <template #default="{ item }">
    <span>{{ item.text }}</span>
  </template>
</List>
```

## Composition API

### Hàm Composable

```
// useMouse.js
import { ref, onMounted, onUnmounted } from 'vue'

export function useMouse() {
  const x = ref(0)
  const y = ref(0)
  function update(e) {
    x.value = e.pageX
    y.value = e.pageY
  }
  onMounted(() => window.addEventListener('mousemove', update))
  onUnmounted(() => window.removeEventListener('mousemove', update))
  return { x, y }
}
```

### Dùng Composable

```
<script setup>
import { useMouse } from './useMouse'

const { x, y } = useMouse()
</script>
<template>
  <p>Mouse: {{ x }}, {{ y }}</p>
</template>
```

### provide / inject

```
// Parent
import { provide, ref } from 'vue'
const theme = ref('dark')
provide('theme', theme)

// Descendant (any depth)
import { inject } from 'vue'
const theme = inject('theme', 'light') // default
```

## Router (Vue Router)

### Định nghĩa routes

```
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
    { path: '/user/:id', component: User },
  ]
})
```

### Điều hướng trong Template

```
<router-link to="/">Home</router-link>
<router-link :to="{ name: 'user', params: { id: 1 } }">
  User 1
</router-link>
<router-view />
```

### Điều hướng bằng code

```
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

router.push('/about')
router.push({ name: 'user', params: { id: 1 } })
console.log(route.params.id)
```

### Tính năng Route

| Command | Description |
|---------|-------------|
| `/user/:id` | Segment động (`route.params.id`) |
| `name: 'user'` | Route có tên để điều hướng bằng code |
| `children: [...]` | Routes lồng nhau |
| `beforeEnter` | Navigation guard theo route |
| `meta: { auth: true }` | Metadata tùy chỉnh cho guards |
| `redirect: '/new-path'` | Chuyển hướng route |

## Lifecycle Hooks

### Thứ tự Hooks

| Command | Description |
|---------|-------------|
| `onBeforeMount` | Trước khi render DOM lần đầu |
| `onMounted` | DOM sẵn sàng (fetch data, thêm listeners) |
| `onBeforeUpdate` | Trước khi re-render do state thay đổi |
| `onUpdated` | Sau khi re-render DOM |
| `onBeforeUnmount` | Trước khi component bị hủy |
| `onUnmounted` | Dọn dẹp (xóa listeners, timers) |

### Cách dùng

```
<script setup>
import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
  console.log('Component mounted')
})

onUnmounted(() => {
  console.log('Cleanup here')
})
</script>
```

## Danh sách & Điều kiện

### v-for

```
<li v-for="item in items" :key="item.id">
  {{ item.name }}
</li>
<li v-for="(item, index) in items" :key="item.id">
  {{ index }}: {{ item.name }}
</li>
<div v-for="(val, key) in obj" :key="key">
  {{ key }}: {{ val }}
</div>
```

*Luôn dùng :key trong v-for để cập nhật DOM hiệu quả*

### v-if vs v-show

| Command | Description |
|---------|-------------|
| `v-if` | Render có điều kiện (thêm/xóa khỏi DOM) |
| `v-else-if` | Chuỗi else-if |
| `v-else` | Nhánh dự phòng |
| `v-show` | Bật/tắt `display: none` (vẫn giữ trong DOM) |

*Dùng v-show khi chuyển đổi thường xuyên, v-if khi ít thay đổi*

### Ví dụ điều kiện

```
<div v-if="status === 'loading'">Loading...</div>
<div v-else-if="status === 'error'">Error!</div>
<div v-else>{{ data }}</div>
```

## Xử lý Form

### v-model cơ bản

```
<input v-model="text" />
<textarea v-model="message"></textarea>
<input type="checkbox" v-model="checked" />
<select v-model="selected">
  <option value="a">A</option>
  <option value="b">B</option>
</select>
```

### Modifier của v-model

| Command | Description |
|---------|-------------|
| `v-model.lazy` | Đồng bộ khi `change` thay vì `input` |
| `v-model.number` | Tự động ép kiểu sang số |
| `v-model.trim` | Tự động xóa khoảng trắng |

### Modifier của Event

| Command | Description |
|---------|-------------|
| `@click.prevent` | Gọi `preventDefault()` |
| `@click.stop` | Gọi `stopPropagation()` |
| `@click.once` | Chỉ kích hoạt tối đa một lần |
| `@keyup.enter` | Chỉ phím Enter |
| `@submit.prevent` | Ngăn submit form mặc định |
