Vue子组件中的setInterval定时器无法停止

1.我在子组件中定义了一个canvas动画,当我显示这个子组件的时候会利用setInterval来呈现出动画效果,可以我发现用clearInterval无法停止动画,请问是什么原因呢?

2.已经尝试了created,updated,mounted,beforeDestroy时候调用setInterval,发现都不行,

尝试在组件中加按钮添加click事件来调用setInterval发现无法触发click事件?

刚接触Vue.js,如果问题问的比较sb,轻喷。

最后,提前感谢大家!


//子组件

<template>

  <div><canvas width="400" height="400" ref="drawing"></canvas></div>

</template>


<script>


    export default {

        mounted(){

            //这里无法停止

            var interval=setInterval(this.drawing,200);

            if(this.width==290){

            //这里不会打印出over,我用v-if隐藏了这个组件后会一直报错, var context=this.$refs.drawing.getContext("2d")这里一直报错,这说明clearInterval一直没起作用

              console.log("over");

              clearInterval(interval);

            }

        },


        name: "canvas-animation",

        data(){

          return {width:100}

        },

        methods:{

         drawing() {

           var context=this.$refs.drawing.getContext("2d");

           context.fillStyle="#409eff";

           context.fillRect(10,10,this.width,this.width);

           this.width=this.width+10;

         }



        }

    }

</script>


<style scoped>


</style>


拉丁的传说
浏览 1806回答 1
1回答

杨__羊羊

因为 if(this.width==290){你只在第一次的时候检测了,后来的 interval 里没有去检测,所以失败。//子组件<template>&nbsp; <div><canvas width="400" height="400" ref="drawing"></canvas></div></template><script>&nbsp; &nbsp; var interval;//new added&nbsp; &nbsp; export default {&nbsp; &nbsp; &nbsp; &nbsp; mounted(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; interval=setInterval(this.drawing,200);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; name: "canvas-animation",&nbsp; &nbsp; &nbsp; &nbsp; data(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return {width:100}&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; methods:{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;drawing() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var context=this.$refs.drawing.getContext("2d");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;context.fillStyle="#409eff";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;context.fillRect(10,10,this.width,this.width);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.width=this.width+10;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(this.width==290){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("over");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clearInterval(interval);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }</script><style scoped></style>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript