'How do I access route query params in component mounted() in vue.js?

I am building a Leaflet map component for a vue.js project, and I would like the map component to be positioned based on the route's query params (pos and z, for position and zoom).

However, when I try to access $route inside mounted() I get nothing. I have resorted to using $nextTick() and delaying the positioning of the map by 100 milliseconds.

This means that

mounted: function(){
    console.log(this.$route);
}

outputs

Object { name: null, meta: {}, path: "/", hash: "", 
         query: {}, params: {}, fullPath: "/", 
         matched: [] }

even though the URL reads http://localhost:3000/index.html#/map?pos=123.81591796875001,6.577303118123887&z=5

Delaying like this below works ok, but doesn't feel right:

var mapEl = L.map(this.$refs.map, opts)
this.$nextTick(function () {
    var c = this;
    setTimeout(function(){
        mapEl.setView(
            (c.$route.query && c.$route.query.pos ?
                c.$route.query.pos.split(',').reverse() : false)
                ||
                c.$props.center
                || [0, 0],
            c.$route.query.z || c.$props.zoom || 1)
        }, 100)
})

What should I do instead of this?



Solution 1:[1]

It's because the navigation is asynchronous. You have to use router.isReady() (a promise function) to wait for vue router initialization complete.

See more: Vue router isReady?Replaced onReady with isReady

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1