vue-router 原理【详解】hash模式 vs H5 history 模式

在这里插入图片描述

hash 模式 【推荐】

路由效果

在不刷新页面的前提下,根据 URL 中的 hash 值,渲染对应的页面

  • http://test.com/#/login 登录页
  • http://test.com/#/index 首页

核心API – window.onhashchange

监听 hash 的变化,触发视图更新

window.onhashchange = (event) => {
  console.log("old url", event.oldURL);
  console.log("new url", event.newURL);
  console.log("hash", location.hash);
  // 执行视图更新(比较复杂,无需深究)
};

hash 的特点

  • hash 变化会触发网页跳转,即浏览器的前进、后退
  • hash 变化不会刷新页面(单页面应用SPA 必需的特点)
  • hash 永远不会提交到 server 端

修改 hash 的方式

  • 通过JS 修改
location.href='#/user'
  • 手动修改 url 里的hash
  • 浏览器前进、后退

H5 history 模式

路由效果

在不刷新页面的前提下,根据 URL 中的 pathname 值,渲染对应的页面。

  • http://test.com/login 登录页
  • http://test.com/index 首页

核心API – history.pushstate 和 window.onpopstate

  • 使用 history.pushstate 跳转页面,避免页面刷新
const state = { name: "index" };
// 使用 history.pushState 跳转页面,浏览器不会刷新页面
history.pushState(state, "", "index");
  • 使用 window.onpopstate 监听浏览器前进、后退
//监听浏览器前进、后退
window.onpopstate = (event) => {
  console.log("onpopstate", event.state, location.pathname);
};

history 的特点

  • 需后端配合
    无论访问怎样的 url ,都返回 index.html 页面

应该选择哪种模式?

  • to B (面向企业的服务)的系统,推荐用 hash,简单易用,对 url 规范不敏感
  • to C(面向消费者的服务)的系统,可以考虑选择 H5 history,但需要服务端支持
  • 能选择简单的,就别用复杂的,要考虑成本和收益

相关推荐

  1. Vue RouterHistory 模式 vs. Hash 模式

    2024-04-14 13:00:02       28 阅读
  2. Vue Router——hash模式history模式

    2024-04-14 13:00:02       28 阅读
  3. Vue Router 路由hashhistory模式

    2024-04-14 13:00:02       34 阅读
  4. Vue的路由实现:hash模式history模式原理

    2024-04-14 13:00:02       55 阅读
  5. vue3 hashhistory模式路由配置

    2024-04-14 13:00:02       37 阅读
  6. hash模式history模式的区别

    2024-04-14 13:00:02       44 阅读
  7. Vue2面试题:说一下路由模式hashhistory的区别?

    2024-04-14 13:00:02       52 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-14 13:00:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-14 13:00:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-14 13:00:02       87 阅读
  4. Python语言-面向对象

    2024-04-14 13:00:02       96 阅读

热门阅读

  1. C++:基于范围的for循环

    2024-04-14 13:00:02       36 阅读
  2. CentOS 7源码包与RPM包软件安装详解

    2024-04-14 13:00:02       39 阅读
  3. Linux 忘记密码解决方法

    2024-04-14 13:00:02       40 阅读
  4. Django的APP应用更名(重命名)流程

    2024-04-14 13:00:02       39 阅读
  5. Qt 2 QMap&QHash&QVector类实例

    2024-04-14 13:00:02       43 阅读
  6. 设计模式,模板方法模式、原型模式

    2024-04-14 13:00:02       41 阅读
  7. MYSQL原理学习篇简记(三)

    2024-04-14 13:00:02       40 阅读
  8. 爬虫开发教程

    2024-04-14 13:00:02       40 阅读