vue router.push : TypeError: onComplete is not a function

Total
1
Shares

I am new to VueJS + Laravel after years using CodeIgniter and trying to understand how things work with Laravel + VueJS. Anyway, I got a test page running with a Vue Loading Layer package that triggers a loading overlay on the onClick event that loads a new page using router.push. I read the documentation that there is 2 additional parameters, ie. onComplete and onAbort for router.push and came up with the following method. Everything work as expected except that I am getting an error in the console.

console error

[vue-router] uncaught error during route navigation:
TypeError: onComplete is not a function

goto method

goTo(routeName) {
    let self = this
    self.$nextTick( function() {

        // Show Vue Loading Layer
        let loader = this.$loading.show({
            loader: 'spinner',
            color: '#e8b30f',
            backgroundColor: '#000',
            opacity: 0.5,
        })

        // Retrieve new page
        self.$router.push(

            // First param : location
            {name: routeName},

            // Second param : onComplete
            setTimeout(() => loader.hide(), 3 * 1000)
        )
    })
}

Even though I got the expected result, I still want to know why that error appears on the console.

Second, is there a better way of doing this? The only reason I used setTimeout() is the new page was loaded too fast for the loading overlay to be shown properly without setting the setTimeout().

Thank you for any help or tips.


Solution

The second param to .push expects a function, what you have passed is

setTimeout(() => loader.hide(), 3 * 1000)

which returns an integer, as you can read here: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Return_value

To fix it, you can wrap it inside a function

() => {
  setTimeout(() => loader.hide(), 3 * 1000)
}

So you goto method will look like

goTo(routeName) {
    let self = this
    self.$nextTick( function() {

        // Show Vue Loading Layer
        let loader = this.$loading.show({
            loader: 'spinner',
            color: '#e8b30f',
            backgroundColor: '#000',
            opacity: 0.5,
        })

        // Retrieve new page
        self.$router.push(

            // First param : location
            {name: routeName},

            // Second param : onComplete
            () => setTimeout(() => loader.hide(), 3 * 1000)
        )
    })
}
Leave a Reply

Your email address will not be published. Required fields are marked *