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?

5
  • this may help you stackoverflow.com/questions/35914069/… Commented Feb 17, 2021 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. Commented Feb 17, 2021 at 11:42
  • need more information, your router config and templates Commented Feb 17, 2021 at 16:19
  • Did you try router's props? Commented Feb 17, 2021 at 22:59
  • @simone this.$route.query in mounted seems to work fine in this codesandbox (demo) Commented Feb 18, 2021 at 6:00

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.