W
W
Wolfcrusher2019-03-24 19:51:08
JavaScript
Wolfcrusher, 2019-03-24 19:51:08

Why does manually changing a route break automatic routing in a Vue app?

Link to a previous application question: How to correctly use a timer as a Vue method (problem when accessing this)?
In the process, the following question arose: as it turned out, when manually changing the route in the browser line, the application starts to "fail" - change the route spontaneously at some points when counter > 0. The application itself works in a loop with changing several similar routes after the end of the countdown. Hence the question - how to make it so that when manually changing the route, the application starts its work correctly, as if from a "clean slate" of the corresponding route. I think there is some kind of snag in the hooks, maybe mounted () is not suitable, maybe you need to use hooks for vue-router, but with others, the situation did not work out better for me.
For other routes, the code is similar:

export default {
  data() {
  	return { counter: 10 }
  },
  methods: {
  timer(counter) {
      let countdown = (counter)=> {
      	if (counter>0) {
          this.counter = counter;
          counter--;
      	  setTimeout((countdown.bind(null,counter)), 1000);
        } else (this.$router.push({ path: '/2'}));
      }
      countdown(counter);
    } 
  },
  mounted() {
    this.timer(this.counter);
  } 
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-03-24
@Wolfcrusher

Because the route has changed, but the timeout has remained. And when you are already on another route, this forgotten timeout suddenly kicks in and... Well, I see.
Save the timeout when setting and reset it when leaving the route:

beforeRouteLeave(to, from, next) {
  clearTimeout(this.timeout);
  next();
},

UPD. Small demo .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question