我正在为vue.js项目构建一个传单地图组件,我希望地图组件根据路由的查询参数(pos和z,用于位置和缩放)进行定位。
然而,当我试图访问mounted()
内的$route
时,我什么也得不到。我已经使用$nextTick()
并将地图的定位延迟100毫秒。
这意味着
mounted: function(){
console.log(this.$route);
}
输出Object { name: null, meta: {}, path: "/", hash: "",
query: {}, params: {}, fullPath: "/",
matched: [] }
,即使URL读取http://localhost:3000/index.html#/map?pos=123.81591796875001,6.577303118123887&z=5
像下面这样延迟可以工作,但感觉不对:
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)
})
我该怎么做呢?
这是因为导航是异步的。你必须使用router.isReady()
(一个承诺函数)来等待vue路由器初始化完成。
看到更多:Vue router isReady,替换onReady为isReady