Quiero escribir un programa con Vue Js. El programa se trata de tener 2 imágenes que se alternan continuamente cada 3 segundos.
Por favor, que alguien me ayude.
Aquí está el código
<script> const app = Vue.createApp({ data() { return{ src : "farkas.jpg" } }, methods: { callFunction: function() { var v = this; setInterval(function() { v.src = "mokus.jpg" }, 3000); } }, mounted () { this.callFunction() } }) const vm = app.mount('#app') </script> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image changer</title> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="app"> <img :src="src"> </div> </body> </html>Puede definir la lista de fuentes en los data :
data() { return { src : "farkas.jpg", srcs: ["farkas.jpg", "mokus.jpg"] } } Y en la función, defina i inicialmente 0, y cada vez que lo incremente/restablezca:
callFunction: function() { let i = 0; setInterval(() => { this.src = this.srcs[i]; if(++i === this.srcs.length) i = 0; }, 3000); }this.interval = setInterval(function() { if (v.src === "mokus.jpg") v.src = "farkas.jpg" else v.src = "mokus.jpg" }, 3000);Y destruye el intervalo con este código en el anzuelo beforeDestroy.
clearInterval(this.interval)Puedes intentar:
const app = Vue.createApp({ data() { return{ currentSrc : 0, srcs: ["img1.jpg", "img2.jpg"] } }, methods: { callFunction: function() { setInterval(() => { this.currentSrc = this.currentSrc === this.srcs.length - 1 ? 0 : this.currentSrc + 1; }, 1000); } }, computed: { src: function(){ return this.srcs[this.currentSrc] } }, mounted () { this.callFunction() } }) const vm = app.mount('#app')