router
router copied to clipboard
第一次跳转,bind事件执行2次
第一次跳转或者手动输入Url,bind的方法会执行2次,直接刷新则不会出现这个问题
我也遇到了...
我也遇到了。。。
同样的问题
解决了这个问题。 当直接访问的时候地址后面不带hash,进行init,先添加了hashchange事件后,进行默认路由的跳转
const hash = util.getHash(location.href);
const route = util.getRoute(this._routes, hash);
this.go(route ? hash : this._default);
此时hash为空,getHash返回的是 /
function getHash(url) {
return url.indexOf('#') !== -1 ? url.substring(url.indexOf('#') + 1) : '/';
}
然后会go到默认路由(一般是/)。
但此时实际hash为空,在go中的enter又有一句
location.hash =
#${url};
导致hash从空变成#/,此处触发了一次hashchange事件,所以会重复触发一次bind。
一个不太优雅的解决方案 首先将getHash中的空hash返回'/'改为返回空
function getHash(url) {
return url.indexOf('#') !== -1 ? url.substring(url.indexOf('#') + 1) : '';
}
然后将init中的默认路由跳转添加一次判断,然后使用location.hash去触发hashchange事件
const hash = util.getHash(location.href);
if(!hash){
location.hash = '#' + this._default;
} else {
const route = util.getRoute(this._routes, hash);
this.go(route ? hash : this._default);
}
return this;
@progrape 希望jf大大看看这样解决有没有什么问题