微信扫一扫打赏支持

VUE实例课程---3、定时显示隐藏元素

VUE实例课程---3、定时显示隐藏元素

一、总结

一句话总结:

定时显示隐藏元素中,定时器函数可以写在mounted中,关闭显示隐藏效果可以用vue的$destroy()方法,可以在beforeDestroy中清除定时器避免内存泄漏
<div id="app">
    <p v-show="isShow">{{msg}}</p>
    <button @click="destroyVue">关闭闪烁</button>
</div>
<script src="../js/vue.js"></script>
<script>
    let vm = new Vue({
        el: '#app',
        data: {
            isShow:false,
            msg: '我有一只小毛驴,我永远也不骑'
        },
        mounted:function () {
            console.log('mounted');
            this.interval_id=setInterval(()=>{
                console.log(this);
                console.log(this.isShow);
                this.isShow=!this.isShow;
            },1000);
        },
        //解决内存泄漏
        beforeDestroy:function(){
            console.log('beforeDestroy');
            clearInterval(this.interval_id);
        },
        methods:{
            destroyVue:function () {
                //直接destroy之后,定时器会造成内存泄漏
                this.$destroy();
            }
        }
    });
    console.log(vm);
</script>

 

 

二、定时显示隐藏元素

博客对应课程的视频位置:

 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>3、定时显示隐藏元素</title>
 6 </head>
 7 <body>
 8 <!--
 9 
10 需求1:
11 让元素隔1s自动显示和隐藏
12 
13 需求2:
14 弄一个按钮关闭上述效果
15 
16 定时显示隐藏元素中,定时器函数可以写在mounted中,关闭显示隐藏效果可以用vue的$destroy()方法,可以在beforeDestroy中清除定时器避免内存泄漏
17 
18 
19 -->
20 <div id="app">
21     <p v-show="isShow">{{msg}}</p>
22     <button @click="destroyVue">关闭闪烁</button>
23 </div>
24 <script src="../js/vue.js"></script>
25 <script>
26     let vm = new Vue({
27         el: '#app',
28         data: {
29             isShow:false,
30             msg: '我有一只小毛驴,我永远也不骑'
31         },
32         mounted:function () {
33             console.log('mounted');
34             this.interval_id=setInterval(()=>{
35                 console.log(this);
36                 console.log(this.isShow);
37                 this.isShow=!this.isShow;
38             },1000);
39         },
40         //解决内存泄漏
41         beforeDestroy:function(){
42             console.log('beforeDestroy');
43             clearInterval(this.interval_id);
44         },
45         methods:{
46             destroyVue:function () {
47                 //直接destroy之后,定时器会造成内存泄漏
48                 this.$destroy();
49             }
50         }
51     });
52     console.log(vm);
53 </script>
54 </body>
55 </html>

 

 

 

 

 

 

 
posted @ 2020-04-21 05:08  范仁义  阅读(488)  评论(0编辑  收藏  举报