THAM KHẢO NHANH VUE.JS
Templates, reactivity, components, Composition API, router
Cú pháp Template
Văn bản & Biểu thức
{{ message }}
{{ count + 1 }}
{{ ok ? 'Yes' : 'No' }}
Directives
| {{ 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
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
| 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
| 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)
Đăng ký Component
Các khối SFC
| <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
Emit Events
Dùng trong component cha
v-model trong Component
Slots
Slot mặc định
Fallback content
Custom content here
Slot có tên
#header>Title
Main content
#footer>Footer
Scoped Slots
#default="{ item }">
{{ item.text }}
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
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
Home
User 1
Đ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
| /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
| 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
Danh sách & Điều kiện
v-for
{{ item.name }}
{{ index }}: {{ item.name }}
{{ key }}: {{ val }}
Luôn dùng :key trong v-for để cập nhật DOM hiệu quả
v-if vs v-show
| 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
Loading...
Error!
{{ data }}
Xử lý Form
v-model cơ bản
Modifier của v-model
| 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
| @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 |