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

简介: 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,但需要服务端支持
  • 能选择简单的,就别用复杂的,要考虑成本和收益
目录
相关文章
|
2月前
|
前端开发 JavaScript 安全
【面试题】路由的两种模式:hash模式和 history模式
【面试题】路由的两种模式:hash模式和 history模式
|
2月前
|
前端开发 搜索推荐 UED
解密前端路由: hash模式vs.history模式
解密前端路由: hash模式vs.history模式
|
存储 移动开发 前端开发
浅谈前端路由原理hash和history
众所周知, hash 和 history 在前端面试中是很常考的一道题目。在学习本文内容之前,周一对 hash 和 history 的认知可能就在 hash 的 url 里面多了个 # ,而 history 就不会。然后,我认知里还有一个是只有 history 才能做前后端分离,而 hash 跟前后端分离没有关系。然而,现实是……
浅谈前端路由原理hash和history
|
2月前
|
资源调度 JavaScript 前端开发
阿珊详解Vue路由的两种模式:hash模式与history模式
阿珊详解Vue路由的两种模式:hash模式与history模式
|
2月前
|
前端开发
前端路由机制实现hash-history
前端路由机制实现hash-history
28 1
|
2月前
|
前端开发 API SEO
vue-router原理以及两种模式区别
vue-router原理以及两种模式区别
21 1
|
2月前
|
移动开发 JavaScript 前端开发
vue-router 中常用的 hash 和 history 路由模式实现原理
vue-router 中常用的 hash 和 history 路由模式实现原理
60 0
|
2月前
|
JavaScript 前端开发 搜索推荐
Vue的路由实现:hash模式 和 history模式原理
Vue的路由实现:hash模式 和 history模式原理
70 0
|
2月前
|
JavaScript 前端开发 API
Vue路由中,history和hash两种模式有什么区别?
Vue路由中,history和hash两种模式有什么区别?
46 0
|
7月前
|
移动开发 JavaScript 前端开发
vue路由的两种模式 hash与history
vue路由的两种模式 hash与history
92 0