Giới thiệu vấn đề
Component Vue 3 thường tải toàn bộ CSS Tailwind dù không dùng. Tăng thời gian khởi tạo. Giải pháp: lazy load CSS và tối ưu reactivity.
Lazy load Tailwind CSS
Import Tailwind trong component thay vì global. Giảm bundle size.
<template>
<div :class="bgClass">Nội dung</div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
export default defineComponent({
setup() {
const bgClass = ref('bg-gray-100');
onMounted(() => {
import('tailwindcss/utilities').then(() => {
bgClass.value = 'bg-blue-500';
});
});
return { bgClass };
}
});
</script>
Giải thích
Dynamic import trả về Promise. Khi tải xong, áp dụng class mới. Không tải toàn bộ utilities.
Tối ưu reactivity với ref và computed
Reactive object lớn gây render lại toàn bộ. Sử dụng ref cho primitive, computed cho derived.
<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
export default defineComponent({
setup() {
const count = ref(0);
const double = computed(() => count.value * 2);
const inc = () => { count.value++; };
return { count, double, inc };
}
});
</script>
Result
Only count thay đổi, double tự cập nhật. Render tối thiểu.
Kiểm tra bundle với vite
Run vite build --mode production để xem kích thước. Sử dụng rollup-plugin-visualizer để phân tích.
vite build --mode production npx rollup-plugin-visualizer dist
Kết luận
Áp dụng lazy load Tailwind, ref/computed giảm render, kiểm tra bundle thường xuyên. Học sâu hơn, cấu trúc dự án chuẩn. Tham khảo khóa học "Lập trình Front-End với VueJS Framework" tại đây.




.png)



