
Sau khi nắm chắc cơ bản (component, props, Pinia, API, routing), bạn nên học những kỹ thuật nâng cao để xử lý ứng dụng phức tạp, tối ưu hiệu năng, và trải nghiệm người dùng mượt mà.
Trong bài này, ta sẽ tìm hiểu:
-
Dynamic component & Async component
-
Teleport
-
Suspense
-
Transition & Animation
-
Directive tự định nghĩa
-
Plugin trong Vue
-
SSR (Server Side Rendering) với Nuxt.js 3
-
Code splitting & Performance optimization
1. Dynamic Component & Async Component
Dynamic component
Dùng <component :is="...">
để render component tùy theo state:
<template> <div> <button @click="view = 'A'">Component A</button> <button @click="view = 'B'">Component B</button> <component :is="viewComponent" /> </div> </template> <script setup> import CompA from './CompA.vue' import CompB from './CompB.vue' import { ref, computed } from 'vue' const view = ref('A') const viewComponent = computed(() => (view.value === 'A' ? CompA : CompB)) </script>
Async component
Dùng khi component nặng, chỉ load khi cần (code-splitting):
import { defineAsyncComponent } from 'vue' const AsyncComp = defineAsyncComponent(() => import('./BigComponent.vue'))
2. Teleport
Giúp render một phần giao diện ra ngoài root (ví dụ modal):
<template> <div> <button @click="show = true">Open Modal</button> <teleport to="body"> <div v-if="show" class="modal"> <p>Đây là modal</p> <button @click="show = false">Đóng</button> </div> </teleport> </div> </template> <script setup> import { ref } from 'vue' const show = ref(false) </script> <style> .modal { position: fixed; top: 40%; left: 40%; background: white; padding: 20px; border: 1px solid #aaa; } </style>
3. Suspense
Dùng để chờ async component hoặc async setup: