[Vuejs]-Vue redirecting. My code is note redirecting to the page i want to

0👍

check Vue Router: Programing Navigation,

As the tutorial said:

router.go(n)

This method takes a single integer as parameter that indicates by
how many steps to go forwards or go backwards in the history stack,
similar to window.history.go(n).

For your use case, you should use router.push

👤Sphinx

0👍

The main problem is that you refer to this variable which in this certain case has different values over the scopes. The common solution is to create a new variable storing this as I did it in the first line of addToApi() method.

Getting to the point, variable router is undefined in the method’s scope. You should use this.$router which refers to the global router object. And as this variable loses its value in then function (change of scope), you want to use vm variable I defined. So your code should finally look like this below:

As pointed in the comment, arrow functions do not carry this variable.

If you want to redirect to a particular route you should use $router.push method instead. (go method was used in Vue Router’s older versions and renamed to push in 2.x)

methods: {
  addToApi() {        
    crypto.randomBytes(20, (err, buff) => {
      let token = buff.toString('hex');
      let sub = this.data.sub;
      let date = Date.now() + 3600000;
      let newData = {
        sub: this.data.sub,
        token: token,
        date: date
      }
      axios.post("http://localhost:3000/api/qrData", newData)
        .then((res) => {
          //after sending the data to back end it should redirect to this route but it doesn't redirect
          this.$router.push('/');
        })
        .catch((err) => {
          console.log(err);
        })
    })
  }
}
}

Leave a comment