- 需要一个类将路由信息保存起来
- 初始化路由信息:
- 判断打开的界面有没有
hash,没有就跳转到#/
- 页面加载完成后和
hash发生变化后都要保存当前地址
- 判断打开的界面有没有路径, 如果没有就跳转到
/
- 加载完成之后和
history发生变化之后都需要保存当前的地址
class myRouteInfo {
constructor(){
this.currentPath = null;
}
}
class myRouter {
constructor(options){
this.mode = options.mode || 'hash';
this.routes = options.routes || [];
// 提取路由信息
/*
{
'/home': Home,
'/about': About
}
* */
this.routesMap = this.createRoutesMap();
// console.log(this.routesMap);
this.routeInfo = new myRouteInfo();
// 初始化默认的路由信息
this.initDefault();
}
initDefault(){
if(this.mode === 'hash'){
// 1.判断打开的界面有没有hash, 如果没有就跳转到#/
if(!location.hash){
location.hash = '/';
}
// 2.加载完成之后和hash发生变化之后都需要保存当前的地址
window.addEventListener('load', ()=>{
this.routeInfo.currentPath = location.hash.slice(1);
});
window.addEventListener('hashchange', ()=>{
this.routeInfo.currentPath = location.hash.slice(1);
console.log(this.routeInfo);
});
}else{
// 1.判断打开的界面有没有路径, 如果没有就跳转到/
if(!location.pathname){
location.pathname = '/';
}
// 2.加载完成之后和history发生变化之后都需要保存当前的地址
window.addEventListener('load', ()=>{
this.routeInfo.currentPath = location.pathname;
});
window.addEventListener('popstate', ()=>{
this.routeInfo.currentPath = location.pathname;
console.log(this.routeInfo);
});
}
}
createRoutesMap(){
return this.routes.reduce((map, route)=>{
map[route.path] = route.component;
return map;
}, {})
}
}
myRouter.install = (Vue, options)=>{
}
export default myRouter;
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。