Kalreg
Kalreg

Reputation: 1012

how to call vue router from inside custom function

I use VueCLI and i do have such code inside methods:

submitCheck: function () {
function authUser() {
  // returns a promise   
}
function uploadFile() {
  // also returns a promise
}

// ...

if ( error !== null ) {
    EventBus.$emit('showError', error)
} else {
    authUser()
        .then(
            function () {
                return uploadFile();
            })
        .then(
            function (data) {
                EventBus.$emit('loaderStop')
                this.$router.push('/awaiting');
        })
        .catch(function(error) {
            EventBus.$emit('loaderStop')
                console.log(error)
        })
}

What i want to achieve is to route to /awaiting if all promises are resolved, but since i use this inside an anonymous function it doesnt have router. I am sure many coders met such a problem and needed to route from inside a function. How to do it?

Kalreg.

Upvotes: 0

Views: 2042

Answers (3)

ESP32
ESP32

Reputation: 8718

The answers from Sandro and Xhua are perfect. I just want to explain, WHY you get the error:

The problem is "this.". It refers to the parent object. So in your case "this." refers to the authUser Object and not to Vue. For your understanding: You could define "var that = this" outside of your authUser object and then use "that." inside. Or you go for the more sophisticated solutions.

Upvotes: 0

Xhua
Xhua

Reputation: 128

You question context is not clear enough. If the code is executed in exponent methods, you can use arrow funciton like (agrs,...) => {...}. Otherwise, if this is not the case, you can use bind function like (function() {}).bind(this). Or just import $router in your code module.

Hope this can help you.

Upvotes: 1

Sandro
Sandro

Reputation: 1061

Multiple ways to handle this, I'd suggest you use arrow functions and learn about their differences to the other function style.

to be clear: replace

function (data) {
    EventBus.$emit('loaderStop')
    this.$router.push('/awaiting');
}

with

data => {
    EventBus.$emit('loaderStop');
    this.$router.push('/awaiting');
}

Upvotes: 2

Related Questions