面试题:vue路由的实现(hash&history)

 history

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>vue 路由中history模式的实现</h1>
    <button id="myBtn">改变url</button>

    <script>
        const myBtn = document.getElementById('myBtn');


        // 页面加载完成后输出当前的路由
        window.addEventListener('DOMContentLoaded', () => {
            console.log('path:', location.pathname); //path: /history.html
        })

        myBtn.addEventListener('click', () => {
            const state = {
                name: 'user'
            }; //user是要去的路由名

            // history对象中的pushState方法
            history.pushState(state, '', 'user.html'); //user路由对应的路径

/* 重点:
            点击按钮后路由变为:http://192.168.43.50:8083/user.html
            输出为:切换路由到了 user

  */           
            // history.pushState(state, title[, url])  title现在还没有用,可写空
            console.log('切换路由到了', 'user'); //切换路由到了 user
        })

        // 监听当前的路由,路由改变时输出当前的路由
        window.onpopstate = (e) => {
            console.log('onpopstate', e.state, location.pathname);
        }
    </script>
</body>

</html>

在当前文件中右键,点击 ,运行live server (不然会报错,造成跨域)

推荐这个方式:因为用live server 有点问题(比如第一行运行的代码,他非说是第10行运行的)

本地的html文件怎么运行在本地服务器上_xiaolinlife的博客-CSDN博客

 选择你要运行的文件

需要后端配合设置无论什么什么路由都显示index.html页面

const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
//这句话重点
  fs.readFile('index.html', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.html" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})

hash

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="myBtn">改变hash的值</button>
</body>
<script>
    const myBtn=document.getElementById('myBtn')

    // 监听hash的变化,当有变化是执行
    window.onhashchange=(e)=>{
        console.log('老url',e.oldURL);//老url http://192.168.43.50:8083/hash.html
        console.log('新url',e.newURL);//新url http://192.168.43.50:8083/hash.html#/user

        console.log('hash',location.hash);//hash #/user
    }
//                美 /ˈkɑːntent; kənˈtent/
//                美 /ˈloʊdɪd/
//                DOMContentLoaded 内容加载完毕
    window.addEventListener('DOMContentLoaded',()=>{
        console.log(location.hash);//输出为空
    })

    myBtn.addEventListener('click',()=>{
        location.href='#/user';
    })
</script>
</html>

1、hash模式

在浏览器中符号“#”,#以及#后面的字符称之为hash,用window.location.hash读取; 特点:hash虽然在URL中,但不被包括在HTTP请求中;用来指导浏览器动作,对服务端安全无用,hash不会重加载页面。 hash 模式下,仅 hash 符号之前的内容会被包含在请求中,如 http://www.xxx.com (opens new window),因此对于后端来说,即使没有做到对路由的全覆盖,也不会返回 404 错误。

2、history模式

history采用HTML5的新特性;且提供了两个新方法:pushState(),replaceState()可以对浏览器历史记录栈进行修改,以及popState事件的监听到状态变更。 history 模式下,前端的 URL 必须和实际向后端发起请求的 URL 一致,如 http://www.xxx.com/items/id。后端如果缺少对 /items/id 的路由处理,将返回 404 错误。Vue-Router 官网里如此描述:“不过这种模式要玩好,还需要后台配置支持……所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值