0

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?

simone
  • 4,667
  • 4
  • 25
  • 47
  • this may help you https://stackoverflow.com/questions/35914069/how-can-i-get-query-parameters-from-a-url-in-vue-js – GhaziBenDahmane Feb 17 '21 at 11:25
  • @GhaziBenDahmane - accessing the route after some time is not a problem: the problem is that at the beginning of ``mounted()`` the route seems to be empty. After 100 ms everythings's ok - see the ``setTimeout()`` workaround. But I don't understand why, and if that's the right thing. – simone Feb 17 '21 at 11:42
  • need more information, your router config and templates – Andrey Nelubin Feb 17 '21 at 16:19
  • Did you try [router's props](https://router.vuejs.org/guide/essentials/passing-props.html#passing-props-to-route-components)? – bigless Feb 17 '21 at 22:59
  • @simone `this.$route.query` in `mounted` seems to work fine in this [codesandbox](https://codesandbox.io/s/naughty-bash-8nu4c?file=/src/components/About.vue) ([demo](https://8nu4c.csb.app/#/about?pos=123.81591796875001,6.577303118123887&z=5)) – tony19 Feb 18 '21 at 06:00

1 Answers1

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 isReadyReplaced onReady with isReady

zxzx1290
  • 26
  • 2