美文网首页
vue路由实现跳转

vue路由实现跳转

作者: 肥羊猪 | 来源:发表于2022-05-22 13:53 被阅读0次

只是实现了跳转,关于vue-router的一些参数懒加载没有嗷~
hash模式的html元素:

 <div>
      <a href="#/home">跳转到首页</a>
      <a href="#/mine">跳转到我的</a>
      <a href="#/list">跳转到列表</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保持不变,监听如下:

 var aList = document.querySelectorAll('a')
        aList.forEach(a => {
            a.addEventListener('click',function(e){
                // 阻止a的默认跳转事件
                e.preventDefault()
                // 往浏览器记录加一个记录
                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'
                }
            })
        });

测试方法:

vscode Live Server插件服务运行index.html文件
右键选择open with live server运行
运行地址http://127.0.0.1:5500/

相关文章

网友评论

      本文标题:vue路由实现跳转

      本文链接:https://www.haomeiwen.com/subject/vxukprtx.html