Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom event still firing after leaving the components vuejs 2

I'm working on a spa project using vue.js. In one component i'm sending ajax request after a while. I"m using vue-router to navigate. when i leaving the route and entering to another component, 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();
        },
    }
like image 940
Alauddin Ahmed Avatar asked Feb 24 '18 06:02

Alauddin Ahmed


People also ask

What is a Vue component?

When not using a build step, a Vue component can be defined as a plain JavaScript object containing Vue-specific options: The template is inlined as a JavaScript string here, which Vue will compile on the fly.

Why should I use Vue instead of HTML?

It's common for an app to be organized into a tree of nested components: This is very similar to how we nest native HTML elements, but Vue implements its own component model that allow us to encapsulate custom content and logic in each component. Vue also plays nicely with native Web Components.

What are props in Vue?

That's where props come in. Props are custom attributes you can register on a component. To pass a title to our blog post component, we must declare it in the list of props this component accepts, using the props option: <!-- BlogPost.vue --> <script> export default { props: ['title'] } </script> <template> <h4> { { title }}</h4> </template>

How to dynamically switch between components in a tabbed interface in Vue?

Sometimes, it's useful to dynamically switch between components, like in a tabbed interface: The above is made possible by Vue's <component> element with the special is attribute: <!-- Component changes when currentTab changes --> <component :is="currentTab"></component> In the example above, the value passed to :is can contain either:


1 Answers

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.

like image 186
Ikbel Avatar answered Oct 16 '22 04:10

Ikbel