es la primera vez que uso Vue.js y necesito hacer una animación muy simple en la primera carga del componente.
Este es mi punto de partida :
<template> <div id="app"> <div class="rect" /> </div> </template> <script> export default { name: "App", components: {}, }; </script> <style lang="scss"> #app { border: 2px solid black; width: 200px; height: 300px; } #app:hover { .rect { background-color: tomato; height: 0%; } } .rect { transition: all 1s ease; background-color: tomato; width: 100%; height: 100%; } </style> Ahora, quiero que en la primera carga, la altura del rectángulo rojo pase de 0% a 100% en 2 segundos y luego debería comportarse como ahora, de modo que al pasar el mouse, la altura se convierta en 0, al pasar el mouse fuera 100%. Para hacerlo, creo una variable isFirstLoad y cambio entre las dos nuevas clases height-0 y height-100 .
Aquí el código:
<template> <div id="app"> <div class="rect" :class="{ 'height-100': isFirstLoad }" /> </div> </template> <script> export default { name: "App", components: {}, data: function () { return { isFirstLoad: true, }; }, mounted() { setTimeout(() => { this.isFirstLoad = false; }, 2000); }, }; </script> <style lang="scss"> #app { border: 2px solid black; width: 200px; height: 300px; .height-0 { height: 0%; } .height-100 { height: 100%; } } #app:hover { .rect { background-color: tomato; height: 0%; } } .rect { transition: all 1s ease; background-color: tomato; width: 100%; // height: 100%; } </style> Funciona en la primera carga, pero luego, la altura recta siempre es 0%. Supongo que porque establezco height-0 siempre. ¿Cómo puedo arreglar?
Prueba como el siguiente fragmento:
new Vue({ el: '#app', data() { return { isFirstLoad: true, } }, methods: { setHeight(toggle) { this.isFirstLoad = toggle; } }, mounted() { setTimeout(() => { this.isFirstLoad = false; }, 2000); } }) Vue.config.productionTip = false Vue.config.devtools = false #app { border: 2px solid black; width: 200px; height: 300px; } #app .height-0 { height: 0%; } #app .height-100 { height: 100%; } #app:hover .rect { background-color: tomato; } .rect { transition: all 1s ease; background-color: tomato; width: 100%; } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app" @mouseover="setHeight(true)" @mouseleave="setHeight(false)"> <div class="rect" :class="isFirstLoad ? 'height-100' : 'height-0'"> </div> </div>