前端路由的实现方式:
1.hash模式
2.history模式
hash模式:
通过监听hashchange事件来实现在页面不刷新的情况下改变内容
总结:
- 不需要后台配合前端独立完成
- 通过监听hashchange事件完成在页面不刷新状态下更新对应的内容渲染
- 地址栏带有# history模式:
- pushState和replaceState可实现在改变url但是不刷新页面的情况下完成对应内容的渲染
- pushState和replaceState压入栈的state属性值可由popState事件中的state对象访问
- pushState和replaceState不会触发popState事件
- 如何实现pushState和repalceState能够出发popState事件
let customEve = function(type){
let originalE = history[type]
return function(){
let currentE = originalE.aplly(this, arguments)
const e = new Event(type)
e.arguments = arguments
window.dispatchEvent(e)
return currentE
}
}
history.pushState = customEve('pushState')
history.pushState({state: 1}, null, '/home')
window.addEventListener('pushState', (e) => {
// 拿到对应的路由参数,做对应的渲染
console.log(e.arguments)
})
- history需要后台配合,在url发生变化后,主动刷新页面,会出现空白页。需要ng配置所有资源默认指向index.html
location / { try_files $uri $uri/ /index.html; }