🏠 Home / Hub

🟢 Lesson 10 — Provide / Inject

← Back to Menu  |  🏠 Hub

1. Problem — Prop Drilling

Parent → Child → Grandchild တွေကို data ဆင်းချပါက props တွေ ထပ်ပတ်ဆင်းရတယ် (prop drilling)

<!-- ❌ Prop Drilling — ကြားတဲ့ component တွေကလည်း prop ဆင်းချရ -->
<Root user="Mg Mg">
  <Layout :user="user">          <!-- ဒီ component မသုံးဘဲ ဆင်းချပဲ -->
    <Sidebar :user="user">       <!-- ဒီ component မသုံးဘဲ ဆင်းချပဲ -->
      <UserAvatar :user="user">  <!-- ဒါပဲ သုံးတာ -->

<!-- ✅ Provide/Inject — ကြားတဲ့ layer တွေ ကျော်ပြီး ဆင်းချနိုင် -->
Root:        provide: { user: 'Mg Mg' }
UserAvatar:  inject: ['user']   ← directly gets it!
🎯 provide/inject က props မပေးဘဲ grandchild ကို data တိုက်ရိုက်ပေးနိုင်တယ်

2. Basic Provide / Inject

// Ancestor (Root/Parent):
provide() {
  return {
    appTitle: 'My App',
    version: '1.0.0',
    theme: 'dark'
  }
}

// Descendant (any depth — child, grandchild, ...):
inject: ['appTitle', 'version', 'theme']

// ပြီးရင် this.appTitle, this.version ဆိုပြီး သုံးလို့ရတယ်
🌳 ROOT (provide data)

Providing: appTitle, version, brand

3. Reactive Provide — Dark Mode Example

Computed property ကို provide လုပ်ရင် reactive ဖြစ်တယ်

// Parent
provide() {
  return {
    // computed ref provide → reactive! ✅
    theme: Vue.computed(() => this.isDark ? 'dark' : 'light'),
    toggleTheme: this.toggle   // method ပါ provide လုပ်နိုင်
  }
}

// Any descendant
inject: ['theme', 'toggleTheme']
// this.theme.value  ← computed ဆိုရင် .value ယူ

4. inject with Default Values

inject: {
  // Object syntax → default value ထည့်လို့ရ
  message: {
    from: 'message',     // key name
    default: 'Hello!'    // fallback if not provided
  },
  config: {
    default: () => ({ debug: false })  // object/array default → factory fn
  }
}

5. Real Use Case — Global Cart State

Cart state ကို Root မှာ provide → Product, Cart component တွေ inject လုပ်သုံး

6. Provide vs Props vs State Management

Method ဘယ်အချိန် သုံး Scope
Props Parent → Direct Child တွေ 1 level
Provide/Inject Component tree ထဲ deep data (theme, user, config) Subtree
Pinia/Vuex App-wide shared state (cart, auth, settings) Global
Emits Child → Parent communication Upward

← Lesson 09  |  Next: Lesson 11 → Transitions

📌 Study Checklist