vue路由實(shí)現(xiàn)跳轉(zhuǎn)

只是實(shí)現(xiàn)了跳轉(zhuǎn),關(guān)于vue-router的一些參數(shù)懶加載沒有嗷~
hash模式的html元素:

 <div>
      <a href="#/home">跳轉(zhuǎn)到首頁</a>
      <a href="#/mine">跳轉(zhuǎn)到我的</a>
      <a href="#/list">跳轉(zhuǎn)到列表</a>
  </div>
  <div id="box"></div>

hash模式的js:

var box = document.getElementById('box')
      var router = [
          {
              path:'/home',
              text:'首頁的組件'
          },
          {
              path:'/mine',
              text:'我的信息的組件'
          },
          {
              path:'/list',
              text:'列表的組件'
          },
      ]
      // hash模式的路由
      window.addEventListener('hashchange',function(){
          console.dir(location.hash)
          var hashPath = location.hash
          // 找出存在router的path
          var component = router.find(h=> '#'+h.path===hashPath)
          if(component){// 存在就賦值
              box.innerHTML = component.text
          }else{
              box.innerHTML = '404'
          }
      })

history模式

html中將href#去掉
js中router保持不變,監(jiān)聽如下:

 var aList = document.querySelectorAll('a')
        aList.forEach(a => {
            a.addEventListener('click',function(e){
                // 阻止a的默認(rèn)跳轉(zhuǎn)事件
                e.preventDefault()
                // 往瀏覽器記錄加一個(gè)記錄
                history.pushState({username:'zy'},'',e.target.href)
                console.dir(location)
                var hashName = location.pathname
                // 找出存在router的path
                var component = router.find(h=> h.path===hashName)
                if(component){
                    box.innerHTML = component.text
                }else{
                    box.innerHTML = '404'
                }
            })
        });

測(cè)試方法:

vscode Live Server插件服務(wù)運(yùn)行index.html文件
右鍵選擇open with live server運(yùn)行
運(yùn)行地址http://127.0.0.1:5500/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容