在vue中如何使用定时器去执行一个数组里的几个函数

直接上代码

<template>
    <div class="hello" style="position: relative">
        <div class="box1" v-show="box1"
             style="width: 100px;height: 100px;background: red;position:absolute; top: 0;left: 100px"></div>
        <div class="box2" v-show="box2"
             style="width: 100px;height: 100px;background: yellow;position:absolute; top: 0;left: 250px"></div>
        <div class="box3" v-show="box3"
             style="width: 100px;height: 100px;background: green;position:absolute; top: 0;left: 400px"></div>
        <div class="buttons_box" style="position: absolute;top: 150px;left: 180px">
            <button @click="box_1" class="active" ref="box_1">显示box1</button>
            <button @click="box_2" ref="box_2">显示box2</button>
            <button @click="box_3" ref="box_3">显示box3</button>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'HelloWorld',
        data() {
            return {
                flag: 1,
                box1: true,
                box2: false,
                box3: false,
                timer: null
            }
        },
        methods: {
            box_1() {
                this.Clearn();
                this.$refs.box_3.className = '';
                this.box1 = true;
                this.box2 = false;
                this.box3 = false;
                this.flag = 2;
                this.$refs.box_1.className = 'active';
                this.Switch();

            },
            box_2() {
                this.Clearn();
                this.$refs.box_1.className = '',
                this.box1 = false;
                this.box2 = true;
                this.box3 = false;
                this.flag = 3;
                this.$refs.box_2.className = 'active';
                this.Switch();
            },
            box_3() {
                this.Clearn();
                this.$refs.box_2.className = '',
                this.box1 = false;
                this.box2 = false;
                this.box3 = true;
                this.flag = 1;
                this.$refs.box_3.className = 'active';
                this.Switch();
            },
            Switch() {
                this.timer = setInterval(() => {
                    if (this.flag == 1) {
                        this.box_1();
                    } else if (this.flag == 2) {
                        this.box_2();
                    } else {
                        this.box_3()
                    }
                }, 2000);
            },
            Clearn() {
                clearInterval(this.timer)
            },
        },
        created() {
            this.Switch();
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    .active {
        background: #0a36e9;
        color: #fff;
    }
</style>
不足之处,请多指教
发布了8 篇原创文章 · 获赞 0 · 访问量 359
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览