refactor(router): 优化路由重定向配置与组件初始化逻辑

- 设置默认重定向路由为 '/'
- 修复路由实例化后未正确调用 init 方法的问题
- 移除不必要的控制台日志输出
- 调整路由守卫中 next 回调的参数传递方式
- 导出 Router 类时增加空格以符合代码风格
- 更新时间戳组件导入方式并移除冗余初始化调用
- 为定时器管理器添加清理功能的日志提示
- 从 BaseComponent 中移除调试日志并修复定时器返回值处理
This commit is contained in:
雨霖铃
2025-12-13 21:52:52 +08:00
parent aaefc9c3fc
commit 8cb9580860
6 changed files with 21 additions and 20 deletions
+2 -4
View File
@@ -12,8 +12,6 @@ export class BaseComponent {
* @param {Function} handler 回调函数 * @param {Function} handler 回调函数
*/ */
bindEvent(target, type, handler) { bindEvent(target, type, handler) {
console.log('Bind 1111;')
// 获取目标元素 // 获取目标元素
const ele = typeof target === 'string' ? document.getElementById(target) : target; const ele = typeof target === 'string' ? document.getElementById(target) : target;
@@ -33,7 +31,7 @@ export class BaseComponent {
* @param {number} ms 定时器间隔时间(毫秒) * @param {number} ms 定时器间隔时间(毫秒)
*/ */
setInterval(fn, ms) { setInterval(fn, ms) {
this._timerManager.setInterval(fn, ms); return this._timerManager.setInterval(fn, ms);
} }
/** /**
@@ -42,7 +40,7 @@ export class BaseComponent {
* @param {number} ms 定时器间隔时间(毫秒) * @param {number} ms 定时器间隔时间(毫秒)
*/ */
setTimeout(fn, ms) { setTimeout(fn, ms) {
this._timerManager.setTimeout(fn, ms); return this._timerManager.setTimeout(fn, ms);
} }
/** /**
+1
View File
@@ -6,6 +6,7 @@ import {Router} from '../modules/Router.js';
const config = { const config = {
routerViewId: 'app', routerViewId: 'app',
stackPages: false, stackPages: false,
redirectRoute: '/',
routes: [ routes: [
{ {
path: '/', path: '/',
+7 -9
View File
@@ -11,8 +11,7 @@ import {
} from '../modules/eventHandlers.js'; } from '../modules/eventHandlers.js';
import {updateTimestamp} from './utils/timestampUtils.js'; import {updateTimestamp} from './utils/timestampUtils.js';
import {timeZoneList} from './const/timezone.js'; import {timeZoneList} from './const/timezone.js';
import {BaseComponent} from './components/BaseComponet.js';
const BaseComponent = window.BaseComponent;
// 获取本地时区 // 获取本地时区
const localTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; const localTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
@@ -20,7 +19,6 @@ const localTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
class Timestamp extends BaseComponent { class Timestamp extends BaseComponent {
constructor() { constructor() {
super(); super();
this.init();
// 定义一个全局变量来保存是否显示毫秒 // 定义一个全局变量来保存是否显示毫秒
this.showMilliseconds = true; this.showMilliseconds = true;
// 定义一个全局变量来保存计时器 // 定义一个全局变量来保存计时器
@@ -33,14 +31,13 @@ class Timestamp extends BaseComponent {
// 初始化时更新一次时间戳 // 初始化时更新一次时间戳
updateTimestamp(currentTimestampValue, this.showMilliseconds); updateTimestamp(currentTimestampValue, this.showMilliseconds);
this.setInterval(() => updateTimestamp(currentTimestampValue, this.showMilliseconds), 100); this.timestampInterval = this.setInterval(() =>
updateTimestamp(currentTimestampValue, this.showMilliseconds),
100);
const timezoneResultSelect = document.getElementById('timezone-result'); const timezoneResultSelect = document.getElementById('timezone-result');
const timezoneInputSelect = document.getElementById('timezone-input'); const timezoneInputSelect = document.getElementById('timezone-input');
// 获取本地时区在列表中的索引
const localTimeZoneIndex = timeZoneList.indexOf(localTimeZone); const localTimeZoneIndex = timeZoneList.indexOf(localTimeZone);
for (let i = 0; i < timeZoneList.length; i++) { for (let i = 0; i < timeZoneList.length; i++) {
if (i === localTimeZoneIndex) { if (i === localTimeZoneIndex) {
// 默认选中本地时区 // 默认选中本地时区
@@ -68,13 +65,14 @@ class Timestamp extends BaseComponent {
'click', 'click',
() => (this.showMilliseconds = handleToggleUnit(this.showMilliseconds)) () => (this.showMilliseconds = handleToggleUnit(this.showMilliseconds))
); );
// 绑定计时器相关按钮事件 // 绑定计时器相关按钮事件
this.bindEvent('stop-timer-btn', 'click', () => handleStopTimer(this.timestampInterval)); this.bindEvent('stop-timer-btn', 'click', () => handleStopTimer(this.timestampInterval));
// 绑定开始计时器事件
this.bindEvent( this.bindEvent(
'start-timer-btn', 'start-timer-btn',
'click', 'click',
() => (this.timestampInterval = handleStartTimer(this.timestampInterval, this.showMilliseconds)) () =>
(this.timestampInterval = handleStartTimer(this.timestampInterval, this.showMilliseconds))
); );
// 绑定时间戳转换按钮事件 // 绑定时间戳转换按钮事件
this.bindEvent('convert-timestamp-to-date-btn', 'click', handleConvertTimestamp); this.bindEvent('convert-timestamp-to-date-btn', 'click', handleConvertTimestamp);
+1
View File
@@ -45,6 +45,7 @@ export class TimerManager {
} }
cleanAll() { cleanAll() {
console.log('cleanAll time or interval');
this.timers.forEach((timerId) => { this.timers.forEach((timerId) => {
window.clearTimeout(timerId); window.clearTimeout(timerId);
window.clearInterval(timerId); window.clearInterval(timerId);
+5 -4
View File
@@ -4,7 +4,7 @@ class Router {
this.beforeFun = null; this.beforeFun = null;
this.afterFun = null; this.afterFun = null;
this.routerViewId = 'app'; this.routerViewId = 'app';
this.redirectRoute = null; this.redirectRoute = '/';
this.stackPages = true; this.stackPages = true;
this.routerMap = []; this.routerMap = [];
@@ -22,6 +22,7 @@ class Router {
this.routerMap = config?.routes || this.routerMap; this.routerMap = config?.routes || this.routerMap;
this.routerViewId = config?.routerViewId || this.routerViewId; this.routerViewId = config?.routerViewId || this.routerViewId;
this.stackPages = config?.stackPages ?? this.stackPages; this.stackPages = config?.stackPages ?? this.stackPages;
this.redirectRoute = config?.redirectRoute || this.redirectRoute;
this.map(); this.map();
// 监听路由变化 // 监听路由变化
@@ -54,10 +55,10 @@ class Router {
*/ */
urlChange() { urlChange() {
const path = location.hash.replace('#', '') || this.redirectRoute; const path = location.hash.replace('#', '') || this.redirectRoute;
console.log('当前路由:', path);
const route = this.routes[path]; const route = this.routes[path];
if (!route) { if (!route) {
// 当前路由不存在时,返回到设置的重定向页面
location.hash = this.redirectRoute; location.hash = this.redirectRoute;
return; return;
} }
@@ -93,7 +94,7 @@ class Router {
} }
const newInstance = await this.scriptManager.getComponentInstance(route.name); const newInstance = await this.scriptManager.getComponentInstance(route.name);
console.log(`newInstance${newInstance}`); console.log(newInstance);
if (newInstance) { if (newInstance) {
this.currentinstance = newInstance; this.currentinstance = newInstance;
if (typeof newInstance.init === 'function') { if (typeof newInstance.init === 'function') {
@@ -108,7 +109,7 @@ class Router {
if (this.beforeFun) { if (this.beforeFun) {
this.beforeFun({ to: route, next: doChange }); this.beforeFun({ to: route, next: doChange });
} else { } else {
doChange().then(r => console.log(r)); doChange().then(r => r);
} }
} }
+2
View File
@@ -53,6 +53,8 @@ export function handleStartTimer(timestampInterval, showMilliseconds) {
const stopTimestampBtn = document.getElementById('stop-timer-btn'); const stopTimestampBtn = document.getElementById('stop-timer-btn');
const currentTimestampValue = document.getElementById('current-timestamp-value'); const currentTimestampValue = document.getElementById('current-timestamp-value');
console.log('开始计时器');
console.log(`timestampInterval:${timestampInterval}`);
// 添加计时器 // 添加计时器
if (timestampInterval) { if (timestampInterval) {
window.timerManager.clearInterval(timestampInterval); window.timerManager.clearInterval(timestampInterval);