手机网站环境承接网站开发 app开发

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,但需要服务端支持
 - 能选择简单的,就别用复杂的,要考虑成本和收益
 
