Listo (Ctrl + Enter para ejecutar) Bootcamp Fullstack »
index.html
Tab = 4 espacios
1
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>provide e inject en Vue 3</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4 bg-light">
  <div id="app" class="card shadow-sm p-4 mx-auto" style="max-width: 520px;">
    <!-- Nivel 1: Ancestro Raíz -->
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h5 class="fw-bold text-success mb-0">Nivel 1: Raíz (Provide)</h5>
      <span class="badge" :class="tema === 'dark' ? 'bg-dark' : 'bg-warning text-dark'">
        Tema: {{ tema.toUpperCase() }}
      </span>
    </div>

    <p class="text-secondary small">
      El estado del tema y la función <code>cambiarTema</code> se suministran con <code>provide()</code> sin pasar props por el nivel intermedio.
    </p>

    <!-- Nivel 2: Componente Intermedio (No conoce ni pasa props de tema) -->
    <contenedor-intermedio></contenedor-intermedio>
  </div>

    <script src="/assets/vendor/vue/vue.global.prod.js"></script>
  <script>
    if (!window.Vue) {
      document.write('<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"><\/script>');
    }
  </script>
  <script>
    const { createApp, ref, provide, inject, readonly } = Vue;

    const app = createApp({
      setup() {
        const tema = ref('dark');

        const alternarTema = () => {
          tema.value = tema.value === 'dark' ? 'light' : 'dark';
        };

        // Proporciona el tema a todo el subárbol:
        provide('temaClave', readonly(tema));
        provide('accionAlternar', alternarTema);

        return { tema };
      }
    });

    // NIVEL 2: Contenedor Intermedio (Puro contenedor, sin props)
    app.component('contenedor-intermedio', {
      template: `
        <div class="p-3 bg-white border rounded mb-2">
          <h6 class="text-secondary mb-2 small fw-bold">Nivel 2: Contenedor (Sin tocar props)</h6>
          <!-- Nivel 3: Nieto -->
          <tarjeta-perfil></tarjeta-perfil>
        </div>
      `
    });

    // NIVEL 3: Componente Nieto que inyecta directamente
    app.component('tarjeta-perfil', {
      setup() {
        // Inyecta directamente desde la raíz:
        const tema = inject('temaClave', 'light');
        const alternar = inject('accionAlternar');

        return { tema, alternar };
      },
      template: `
        <div class="p-3 rounded border" :class="tema === 'dark' ? 'bg-dark text-white' : 'bg-light text-dark'">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <h6 class="mb-0 fw-bold">Nivel 3: Nieto (Inject Directo)</h6>
              <small class="opacity-75">Recibió el tema directamente desde la raíz.</small>
            </div>
            <button @click="alternar" class="btn btn-sm btn-primary">
              Alternar
            </button>
          </div>
        </div>
      `
    });

    app.mount('#app');
  </script>
</body>
</html>
Haz clic para editar este código
Vista Previa
Navegador / HTML5