前端路由hash和history

hash模式

使用window.location.hash属性以及onhashchange事件,实现监听浏览器地址的hash值变化,执行相应的js切换网页

属性含义例子
location.href完整的URL字符串https://www.example.com:8080/pathname/?search=test#hash
location.protocol协议部分https:
location.hostname主机名www.example.com
location.port端口号8080
location.host主机名和端口号www.example.com:8080
location.pathname路径部分/post/6993840419041706014
location.search查询字符串部分?search=test
location.hash哈希值#hash

window.location还提供了一些方法:

方法含义
location.assign(url)加载指定的URL
location.replace(url)替换当前的 URL,但不会在历史记录中创建新的条目。即用户无法通过浏览器的“后退”按钮返回到之前的页面。
location.reload(forceReload)重新加载当前页面。forceReload 参数为 true 时会强制从服务器重新加载页面(而不是从缓存中加载)。
location.toString()返回当前 URL 的字符串表示。
// 获取当前 URL 的各种部分
console.log(window.location.href);      // 输出完整的 URL
console.log(window.location.protocol);  // 输出协议部分
console.log(window.location.host);      // 输出主机和端口号
console.log(window.location.hostname);  // 输出主机名
console.log(window.location.port);      // 输出端口号
console.log(window.location.pathname);  // 输出路径
console.log(window.location.search);    // 输出查询字符串
console.log(window.location.hash);      // 输出哈希
console.log(window.location.origin);    // 输出源 URL

// 改变 URL 并重新加载页面
window.location.href = 'https://www.example.com';

// 替换当前 URL,不会在历史记录中创建新的条目
window.location.replace('https://www.example.com');

// 重新加载页面
window.location.reload();     // 从缓存中重新加载
window.location.reload(true); // 强制从服务器重新加载

history模式

History API是H5提供的新特性,允许开发者直接更改前端路由,即更新浏览器URL地址而不重新发起请求。它表示当前窗口的浏览历史。当发生改变时,只会改变页面的路径,不会刷新页面。 History 对象保存了当前窗口访问过的所有页面网址。通过 history.length 可以得出当前窗口一共访问过几个网址。 由于安全原因,浏览器不允许脚本读取这些地址,但是允许在地址之间导航。 浏览器工具栏的“前进”和“后退”按钮,其实就是对 History 对象进行操作。

属性含义
history.length历史记录中的条目数
history.state历史记录条目的状态对象

window.history 还提供了一些方法:

方法含义例子
history.pushState(state, title, url)将一个状态对象添加到历史记录栈中window.history.pushState({ page: 1 }, “title 1”, “/page1”);
history.replaceState(state, title, url)修改当前历史记录条目的状态对象、标题和 URLwindow.history.replaceState({ page: 2 }, “title 2”, “/page2”);
history.back()加载历史记录列表中的前一个 URL,与用户点击浏览器的后退按钮相同。window.history.back();
history.forward()加载历史记录列表中的下一个 URL,与用户点击浏览器的前进按钮相同。window.history.forward();
history.go(delta)根据 delta 值加载历史记录中的特定页面。delta: 为正值时前进,为负值时后退。window.history.go(-1); // 后退一页
window.history.go(1); // 前进一页

history代码实现

class CustomHistory {
  constructor() {
    this.stack = [];
    this.currentIndex = -1;
  }

  pushState(state, title, url) {
    if (this.currentIndex < this.stack.length - 1) {
      this.stack = this.stack.slice(0, this.currentIndex + 1);
    }
    this.stack.push({ state, title, url });
    this.currentIndex++;
    this.updateUrl(url);
  }

  replaceState(state, title, url) {
    if(this.currentIndex >= 0){
      this.stack[this.currentIndex] = { state, title, url };
      this.updateUrl(url);
    } else {
        this.pushState(state, title, url);
    }
  }

  go(index) {
    const newIndex = this.currentIndex + index;
    if (newIndex >= 0 && newIndex < this.stack.length) {
      this.currentIndex = newIndex;
    }
  }

  back(){
    if(this.currentIndex > 0){
      this.currentIndex--;
      this.applyState();
    }
  }
  
  forward(){
    if(this.currentIndex < this.stack.length - 1){
      this.currentIndex++;
      this.applyState();
    }
  }

  applyState() {
    const currentState = this.stack[this.currentIndex];
    this.updateUrl(currentState.url);
    // this.dispatchPopStaet(currentState);
  }

  updateUrl(url) {
    console.log("🚀 ~ CustomHistory ~ updateUrl ~ url:", url)
  }

  dispatchPopStaet(state){
    const event = new CustomEvent('popstate', { detail: state });
    window.dispatchEvent(event);
  }
}

// Usage example:
const customHistory = new CustomHistory();

customHistory.pushState({ page: 1 }, "Title 1", "/page1");
customHistory.pushState({ page: 2 }, "Title 2", "/page2");
customHistory.replaceState({ page: 3 }, "Title 3", "/page3");

// window.addEventListener('popstate', (event) => {
//     console.log('Popstate event:', event.detail);
// });

customHistory.back(); // Navigating to: /page1
customHistory.forward(); // Navigating to: /page3
customHistory.go(-1); // Navigating to: /page1
  • 24
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值