使用 setinterval 更改 Vue JS 图像

Vue JS image changing with setinterval

我想用Vue Js写一个程序。该程序是关于有 2 个图像,每 3 秒连续交替。

请有人帮助我。

这是代码

<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>

您可以在 data:

中定义源列表
data() {
  return {
    src : "farkas.jpg",
    srcs: ["farkas.jpg", "mokus.jpg"]
  }
}

并且在函数中,定义i初始为0,每次increment/reset它:

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);

并在 beforeDestroy 挂钩中使用此代码销毁间隔。

clearInterval(this.interval)

你能试试吗:

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