Home > Software engineering >  Vue JS image changing with setinterval
Vue JS image changing with setinterval

Time:11-28

I want to write a program with Vue Js. The program is about having 2 images that continuously alternate every 3 seconds.

Please someone help me.

Here is the code

<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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can define the list of sources in the data:

data() {
  return {
    src : "farkas.jpg",
    srcs: ["farkas.jpg", "mokus.jpg"]
  }
}

And in the function, define i initially 0, and every time increment/reset it:

callFunction: function() {
  let i = 0;
  setInterval(() => {
    this.src = this.srcs[i];
    if(  i === this.srcs.length) i = 0;
  }, 3000);
}

CodePudding user response:

this.interval = setInterval(function() {
    if (v.src === "mokus.jpg") v.src = "farkas.jpg"
    else v.src = "mokus.jpg" }, 3000);

And destroy the interval with this code in the beforeDestroy hook.

clearInterval(this.interval)

CodePudding user response:

Can You Try:

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')
  • Related