Configuré un código de demostración para vue 3, para actualizar el estilo en línea a un objeto calculado, pero no se actualiza.
<!DOCTYPE html> <html> <head> <title>Demo</title> <link rel="stylesheet" href="main.css"> <script src="https://cdn.jsdelivr.net/npm/vue@3.2.26/dist/vue.global.prod.min.js"></script> </head> <body> <div id="map"> <div id="infantry" class="unit" :style="style"> Position: {{ x }} {{ y }} </div> </div> <script> const Infantry = { data() { return { x: 0, y: 0 } }, mounted() { setInterval(() => { this.x++; this.y++; }, 1000); }, computed : { style() { return { top : this.x }; } } } Vue.createApp(Infantry).mount('#infantry'); </script> </body> </html>Esta parte no funciona
:style="style" Compruebo el dom, y no establece el estilo para usar top . ¿Alguien sabe lo que está mal?
El problema es que está vinculando un atributo del elemento donde monta la aplicación vue y luego agrega px al valor superior devuelto:
.unit { position: absolute } <!DOCTYPE html> <html> <head> <title>Demo</title> <link rel="stylesheet" href="main.css"> <script src="https://cdn.jsdelivr.net/npm/vue@3.2.26/dist/vue.global.prod.min.js"></script> </head> <body> <div id="map"> <div class="unit" :style="style"> Position: {{ x }} {{ y }} </div> </div> <script> const Infantry = { data() { return { x: 0, y: 0 } }, mounted() { setInterval(() => { this.x++; this.y++; }, 1000); }, computed: { style() { return { top: this.x + "px" }; } } } Vue.createApp(Infantry).mount('#map'); </script> </body> </html>