5 分钟理解 vue-router 原理

vue-router 原理

路由原理,是面试非常频繁常问的一个问题

面试官:你了解vue路由原理吗 ?
回答 :是利用浏览器的 history api、
面试官:具体是怎么实现的呢?
回 答 :坏了。。。。。。

  • 针对路由的两种模式(hash模式、history模式)原理是不一样的

Hash 模式

  • hash模式是比较简单的, 在浏览器后拼接 #开头的 , 浏览器是不会触发更新的;
  • 可以 hashchange 去触发监听,再去加载对应的 .vue文件;
<a href='#/page1'>页面1</a>
<a href='#/page2'>页面2</a>
window.addEventListener('hashchange',function(e){
    
    
     console.log(location.hash);
})

history模式

  • history 模式需要和后端沟通,在 url 后面拼接什么,都返回该页面;
  • 进入页面后的切换,则需要 pushStatereplaceState 不触发浏览器刷新方法;
  • pushState(添加历史中) ,replaceState(替换当前历史),其他功能相同;
<button onclick='push()'>page1</button>
<button onclick='replace()'>page2</button>
<script>
	function push(){
      
       window.history.pushState({
      
       page:1 },'','/page1') }
	function replace(){
      
       window.history.replaceState({
      
       page:2 },'','/page2') }
</script>
  • 浏览器没办法去监听pushStatereplaceState 方法,所以需要手动写一个;
  • 通过dispatchEvent 触发自定义事件。
window.history.pushState = myHistoryEvent('pushState');
window.history.replaceState = myHistoryEvent('replaceState')

function myHistoryEvent(type){
    
    
     const myEvent = history[type]
     return function () {
    
    
        const e = new Event(type)
        e.arguments = arguments;
        window.dispatchEvent(e)
        return myEvent.apply(this, arguments)
      }
 }

window.addEventListener('pushState',function(e){
    
      console.log(e)   })
window.addEventListener('replaceState',function(e){
    
      console.log(e)  })
  • 最后我们可以 搭建本地服务进行测试;
  • 可以通过 http-server 或 启动 vue 项目 等

猜你喜欢

转载自blog.csdn.net/weixin_42232622/article/details/131744763