← 返回首页
Vue-cli3基础教程(十五)
发表时间:2021-07-21 15:45:45
vue-router的history模式原理

history api 是可以改变url地址,并且会添加到浏览记录的历史里面,返回的时候还会返回相应的地址。vue-router的history模式就是使用history api实现的。

把上小节小例改写如下:

注意:这种实现方式无法实现刷新页面,因为history的URL资源不是真实存在的。

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #router-view{
            margin: 0px auto;
            background: lightblue;
            width: 100%;
            height: 100vh;
            border: 1px solid #ccc;
            text-align: center;
        }
    </style>
</head>
<body>

<div id="router-view">

</div>

<script>

    let routers=[
        {
            path:'/users',
            content:`<h2>用户首页</h2><hr><div><a href='javascript:goto("/users/list")'>用户列表</a> | <a href='javascript:goto("/users/detail")'>用户详情</a></div>`
        },
        {
            path:'/users/list',
            content:`<h2>用户列表页面</h2><hr><div><a href='javascript:goto("/users/list")'>用户列表</a> | <a href='javascript:goto("/users/detail")'>用户详情</a></div>`
        },
        {
            path:'/users/detail',
            content:`<h2>用户详情页面</h2><hr><div><a href='javascript:goto("/users/list")'>用户列表</a> | <a href='javascript:goto("/users/detail")'>用户详情</a></div>`
        }
    ]

    function goto(url){
        history.pushState(null,null,url);
        doRoute();
    }

    function doRoute(){
        let currentPath = location.pathname;
        console.log(currentPath);
        let routerView =  document.querySelector("#router-view");
        let target =  routers.find(item=>{return item.path == currentPath})

        console.log(target);
        if(!target){
            routerView.innerHTML = `<h2>404</h2><hr><div><a href='javascript:goto("/users/list")'>用户列表</a> | <a href='javascript:goto("/users/detail")'>用户详情</a></div>`;
            return;
        }
        routerView.innerHTML = target.content;

    }
    window.onpopstate = (e)=>{
        doRoute();
    }
    window.history.pushState(null,null,'/users');
    doRoute();

</script>
</body>
</html>

运行效果:

hash模式与history模式对比

项目 hash模式 history模式
url显示 有# ,不美观 无#,美观
刷新页面 可以加载到hash值对应的页面 会出现404错误,结合服务器entry-file或者try-file解决
支持版本 支持低版本浏览器和IE浏览器 HTML5新特征