网络编程
位置:首页>> 网络编程>> JavaScript>> 关于vue中hash和history的区别与使用图文详解

关于vue中hash和history的区别与使用图文详解

作者:cc.ChenLy  发布时间:2024-05-13 09:14:31 

标签:hash,history,区别

一、区别

1、 history和hash都是利用浏览器的两种特性实现前端路由,history是利用浏览历史记录栈的API实现,hash是监听location对象hash值变化事件来实现

2、 history的url没有’#'号,hash反之

3、 相同的url,history会触发添加到浏览器历史记录栈中,hash不会触发,history需要后端配合,如果后端不配合刷新新页面会出现404,hash不需要

4、
HashRouter的原理:通过window.onhashchange方法获取新URL中hash值,再做进一步处理 HistoryRouter的原理:通过history.pushState 使用它做页面跳转不会触发页面刷新,使用window.onpopstate 监听浏览器的前进和后退,再做其他处理

二、使用

举例说明history模式

1、现有一个这样的页面(Vue2)

关于vue中hash和history的区别与使用图文详解

关于vue中hash和history的区别与使用图文详解

2、设置路由模式

关于vue中hash和history的区别与使用图文详解

3、打包

使用webpack的npm build命令,生成以下文件

关于vue中hash和history的区别与使用图文详解

4、模拟一个服务器(nodejs的express)

初始化

关于vue中hash和history的区别与使用图文详解

关于vue中hash和history的区别与使用图文详解

调试

关于vue中hash和history的区别与使用图文详解

关于vue中hash和history的区别与使用图文详解

5、把打包好的文件放到服务器

关于vue中hash和history的区别与使用图文详解

6、访问,路由跳转不涉及网络请求

关于vue中hash和history的区别与使用图文详解

7、刷新页面,资源请求失败,发送网络请求/MyHome/message/details/1/message001失败

因为服务器上没有这个请求(history模式存在这个问题,hash模式则无)

关于vue中hash和history的区别与使用图文详解

8、解决办法

使用connect-history,根据npm官方文档

关于vue中hash和history的区别与使用图文详解

关于vue中hash和history的区别与使用图文详解

9、再次调试,刷新后依旧没问题

关于vue中hash和history的区别与使用图文详解

总结 

来源:https://blog.csdn.net/weixin_46589442/article/details/125796515

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com