🏠 Home / Hub

🟢 Lesson 09 — Dynamic Components & keep-alive

← Back to Menu  |  🏠 Hub

1. <component :is> — Dynamic Switch

String name တစ်ခုနဲ့ render မယ့် component ကို runtime မှာ switch လုပ်တယ်

<!-- currentTab = 'HomePanel' | 'ProfilePanel' | 'SettingsPanel' -->
<component :is="currentTab"></component>

<!-- v-if တွေ ကြိုးကြိုး ရေးစရာမလို —  -->
<!-- <home-panel v-if="tab==='home'">  ❌ ရှည် -->
<!-- <component :is="tab">             ✅ သပ် -->

Current: :is="{{ currentTab }}"

2. <keep-alive> — State Preserved

Switch လုပ်တိုင်း component re-create မဖြစ်ဘဲ state ကို မှတ်ထားတယ်

<!-- WITHOUT keep-alive: state ပျောက်တယ် ❌ -->
<component :is="currentTab"></component>

<!-- WITH keep-alive: state မှတ်ထားတယ် ✅ -->
<keep-alive>
  <component :is="currentTab"></component>
</keep-alive>
💡 Counter တွေ ရေတွက်ပြီး Tab switch လုပ်ကြည့်ပါ — keep-alive က ဂဏန်း မမေ့ဘူး!

❌ Without keep-alive

Switch လုပ်ရင် counter reset ဖြစ်တယ်!

✅ With keep-alive

Switch လုပ်ရင် counter မှတ်ထားတယ်!

3. keep-alive :include / :exclude

Component တစ်ချို့ကိုပဲ cache လုပ်ဖို့ — name နဲ့ စစ်

<!-- Name တူတဲ့ component တွေပဲ cache -->
<keep-alive include="HomePanel,ProfilePanel">
  <component :is="current"></component>
</keep-alive>

<!-- Name တူတဲ့ component တွေ cache မလုပ် -->
<keep-alive exclude="SettingsPanel">
  <component :is="current"></component>
</keep-alive>

<!-- Max cache count -->
<keep-alive :max="3">
  <component :is="current"></component>
</keep-alive>
💡 include="CounterA" ထည့်ထားတယ် — CounterA ပဲ state မှတ်မယ်၊ CounterB မှတ်မယ်မဟုတ်

CounterA = cached ✅  |  CounterB = not cached ❌

4. activated / deactivated Hooks

keep-alive component မှာ mounted/unmounted မဟုတ်ဘဲ activated/deactivated ကိုသုံး

// keep-alive component ထဲမှာ:
activated() {
  console.log('Component shown (from cache)')
  this.startTimer()
},
deactivated() {
  console.log('Component hidden (cached)')
  this.stopTimer()
}

// mounted()  → first time ပဲ run
// activated() → cache ကနေ ပြန်ဝင်တိုင်း run
{{ l }}
Switch tabs to see lifecycle logs...

5. Async / Lazy Component

Component ကို လိုအပ်မှ load လုပ်တယ် — large component တွေအတွက် performance ကောင်း

import { defineAsyncComponent } from 'vue'

const HeavyChart = defineAsyncComponent(() =>
  import('./components/HeavyChart.vue')
)

// CDN version (simulate):
const LazyComp = defineAsyncComponent({
  loader: () => new Promise(resolve => {
    setTimeout(() => resolve({ template: '<p>Loaded!</p>' }), 1500)
  }),
  loadingComponent: { template: '<p>Loading...</p>' },
  errorComponent:   { template: '<p>Error!</p>' },
  delay: 200,      // show loading after 200ms
  timeout: 5000    // error after 5s
})

← Lesson 08  |  Next: Lesson 10 → Provide / Inject

📌 Study Checklist