Vue 3 Composition API - Hướng dẫn chi tiết cho người mới bắt đầu
Tìm hiểu về Composition API trong Vue 3, cách sử dụng và so sánh với Options API truyền thống
Vue 3 đã giới thiệu Composition API như một cách mới để tổ chức và tái sử dụng code. Trong bài viết này, chúng ta sẽ tìm hiểu chi tiết về Composition API và cách áp dụng nó trong dự án thực tế.
Composition API là gì?
Composition API là một tập hợp các API cho phép chúng ta sử dụng các tính năng của Vue theo kiểu functional. Nó giúp tổ chức logic tốt hơn, đặc biệt với các component phức tạp.
Ưu điểm của Composition API
- Tái sử dụng logic tốt hơn: Dễ dàng chia sẻ logic giữa các components
- Type inference tốt hơn: Hỗ trợ TypeScript tốt hơn
- Tổ chức code: Nhóm code theo feature thay vì options
- Performance: Hiệu suất tốt hơn trong một số trường hợp
Setup Function
Setup function là điểm bắt đầu của Composition API:
<template>
<div>{{ count }}</div>
<button @click="increment">Tăng</button>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
function increment() {
count.value++
}
return {
count,
increment
}
}
}
</script>
Reactive và Ref
Vue 3 cung cấp hai cách để tạo reactive state:
Ref
import { ref } from 'vue'
const count = ref(0)
console.log(count.value) // 0
count.value++
Reactive
import { reactive } from 'vue'
const state = reactive({
count: 0,
message: 'Hello'
})
state.count++
Computed và Watch
Computed Properties
import { ref, computed } from 'vue'
const firstName = ref('Dung')
const lastName = ref('QB')
const fullName = computed(() => {
return `${firstName.value} ${lastName.value}`
})
Watchers
import { ref, watch } from 'vue'
const question = ref('')
const answer = ref('Câu hỏi thường có dấu ?')
watch(question, async (newQuestion) => {
if (newQuestion.includes('?')) {
answer.value = 'Đang suy nghĩ...'
// Gọi API
answer.value = await fetchAnswer()
}
})
Lifecycle Hooks
Trong Composition API, lifecycle hooks có prefix "on":
import { onMounted, onUpdated, onUnmounted } from 'vue'
export default {
setup() {
onMounted(() => {
console.log('Component đã mount')
})
onUpdated(() => {
console.log('Component đã update')
})
onUnmounted(() => {
console.log('Component đã unmount')
})
}
}
Composables
Composables là các function tái sử dụng logic:
// useCounter.js
import { ref } from 'vue'
export function useCounter() {
const count = ref(0)
function increment() {
count.value++
}
function decrement() {
count.value--
}
return {
count,
increment,
decrement
}
}
// Component
import { useCounter } from './useCounter'
export default {
setup() {
const { count, increment, decrement } = useCounter()
return {
count,
increment,
decrement
}
}
}
Script Setup
Vue 3.2+ giới thiệu <script setup> - syntax ngắn gọn hơn:
<script setup>
import { ref, computed } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">
Count: {{ count }}, Doubled: {{ doubled }}
</button>
</template>
So sánh với Options API
Options API
export default {
data() {
return {
count: 0
}
},
computed: {
doubled() {
return this.count * 2
}
},
methods: {
increment() {
this.count++
}
}
}
Composition API
import { ref, computed } from 'vue'
export default {
setup() {
const count = ref(0)
const doubled = computed(() => count.value * 2)
function increment() {
count.value++
}
return {
count,
doubled,
increment
}
}
}
Best Practices
- Sử dụng composables để tái sử dụng logic
- Đặt tên rõ ràng cho các biến và function
- Nhóm code theo feature thay vì theo type
- Sử dụng TypeScript để có type safety tốt hơn
- Không lạm dụng - Options API vẫn tốt cho component đơn giản
Kết luận
Composition API mang lại nhiều lợi ích cho việc phát triển ứng dụng Vue quy mô lớn. Tuy nhiên, không phải lúc nào cũng cần sử dụng nó. Hãy cân nhắc dựa trên độ phức tạp của component và nhu cầu tái sử dụng code.
Công cụ dùng kèm bài này
Dũng QB
Lập trình viên fullstack ở Sài Gòn, viết code từ 2014. Chủ yếu viết phần mềm cho người làm marketing và bán hàng trên Facebook, TikTok, Telegram.
Về mìnhBình luận
Chưa có bình luận nào. Bạn là người đầu tiên.