最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - custom event still firing after leaving the components vuejs 2 - Stack Overflow

programmeradmin3浏览0评论

I'm working on a spa project using vue.js. In one ponent i'm sending ajax request after a while. I"m using vue-router to navigate. when i leaving the route and entering to another ponent, the ajax request still executing. How do i prevent/destroy the event executing? Here is my code example:

    export default {
        data() {
            return {
            };
        },
        methods: {
            onLoad() {
                setInterval(function(){
                    //sending ajax request
                }, 5000);
            },
        },
        mounted() {
            this.onLoad();
        },
    }

I'm working on a spa project using vue.js. In one ponent i'm sending ajax request after a while. I"m using vue-router to navigate. when i leaving the route and entering to another ponent, the ajax request still executing. How do i prevent/destroy the event executing? Here is my code example:

    export default {
        data() {
            return {
            };
        },
        methods: {
            onLoad() {
                setInterval(function(){
                    //sending ajax request
                }, 5000);
            },
        },
        mounted() {
            this.onLoad();
        },
    }
Share Improve this question edited Feb 24, 2018 at 7:06 Ikbel 7,8513 gold badges36 silver badges46 bronze badges asked Feb 24, 2018 at 6:51 Alauddin AhmedAlauddin Ahmed 1,1852 gold badges17 silver badges38 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

You need to save the interval ID in your Vue instance so that you can remove it later by calling clearInterval. Here is how you can achieve that:

export default {
  methods: {
    onLoad() {
      this.intervalId = setInterval(() => {
        //sending ajax request
      }, 5000)
    }
  },
  mounted() {
    this.onLoad()
  },
  beforeDestroy() {
    clearInterval(this.intervalId)
  }
}

EDIT: intervalId doesn't need to be reactive.

发布评论

评论列表(0)

  1. 暂无评论