Listo (Ctrl + Enter para ejecutar) Bootcamp Fullstack »
index.html
Tab = 4 espacios
1
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Lifecycle Hooks 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: 500px;">
    <h5 class="fw-bold text-success mb-3">Ciclo de Vida: onMounted & onUnmounted</h5>

    <!-- Botón para montar/desmontar el cronómetro hijo -->
    <div class="mb-3 d-flex justify-content-between align-items-center">
      <span class="small text-muted">Alternar Componente Hijo:</span>
      <button @click="mostrarCronometro = !mostrarCronometro" class="btn btn-sm" :class="mostrarCronometro ? 'btn-danger' : 'btn-success'">
        {{ mostrarCronometro ? 'Desmontar Componente' : 'Montar Componente' }}
      </button>
    </div>

    <!-- Contenedor condicional -->
    <div v-if="mostrarCronometro" class="p-3 bg-white border rounded text-center mb-3">
      <p class="text-secondary small mb-1">Segundos activo en pantalla:</p>
      <h2 class="display-5 fw-bold text-primary mb-2">{{ segundos }}s</h2>
      <div class="badge bg-success">Timer activo en memoria</div>
    </div>

    <div v-else class="alert alert-secondary text-center py-3 mb-3">
      El cronómetro está <strong>desmontado</strong> (intervalo destruido sin fugas).
    </div>

    <div class="p-2 bg-dark text-light rounded font-monospace small" style="font-size: 0.78rem;">
      <div class="text-muted border-bottom border-secondary pb-1 mb-1">&gt;_ Registro de Hooks:</div>
      <div v-for="(log, i) in bitacora" :key="i">{{ log }}</div>
    </div>
  </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, onMounted, onUnmounted, onUpdated } = Vue;

    createApp({
      setup() {
        const mostrarCronometro = ref(true);
        const segundos = ref(0);
        const bitacora = ref([]);
        let intervalId = null;

        const agregarLog = (mensaje) => {
          bitacora.value.push(`[${new Date().toLocaleTimeString()}] ${mensaje}`);
          if (bitacora.value.length > 5) bitacora.value.shift();
        };

        // 1. Hook onMounted
        onMounted(() => {
          agregarLog('onMounted: Componente montado en el DOM');
          intervalId = setInterval(() => {
            if (mostrarCronometro.value) {
              segundos.value++;
            }
          }, 1000);
        });

        // 2. Hook onUpdated
        onUpdated(() => {
          agregarLog(`onUpdated: DOM sincronizado (${segundos.value}s)`);
        });

        // 3. Hook onUnmounted
        onUnmounted(() => {
          agregarLog('onUnmounted: Limpiando intervalo');
          if (intervalId) clearInterval(intervalId);
        });

        return {
          mostrarCronometro,
          segundos,
          bitacora
        };
      }
    }).mount('#app');
  </script>
</body>
</html>
Haz clic para editar este código
Vista Previa
Navegador / HTML5