javascript原生实现Vue.js路由

版权声明:黄河爱浪,[email protected], https://blog.csdn.net/u013350495/article/details/83034213

javascript 原生实现 Vue.js的路由切换功能,模拟单页应用

上效果图:

  

源码如下:

<!--
    author:helang
    Email:[email protected]
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="author" content="[email protected]">
    <title>原生模拟Vue路由切换</title>
    <style type="text/css">
        .router_box,#router-view{
            max-width: 1000px;
            margin: 50px auto;
            padding: 0 20px;
        }
        .router_box>a{
            padding: 0 10px;
            color: #42b983;
        }
    </style>
</head>
<body>
<div class="router_box">
    <a href="/home" class="router">主页</a>
    <a href="/news" class="router">新闻</a>
    <a href="/team" class="router">团队</a>
    <a href="/about" class="router">关于</a>
</div>
<div id="router-view"></div>
<script type="text/javascript">
    function Vue(parameters) {
        let vue={};
        vue.routes=parameters.routes || [];
        vue.init=function () {
            document.querySelectorAll(".router").forEach((item,index)=>{
                item.addEventListener("click",function(e){
                    let event = e|| window.event;
                    event.preventDefault();
                    window.location.hash=this.getAttribute("href");
                },false);
            });


            window.addEventListener("hashchange",()=>{
                vue.routerChange();
            });


            vue.routerChange();
        };
        vue.routerChange=()=>{
            let nowHash=window.location.hash;
            let index=vue.routes.findIndex((item,index)=>{
                return nowHash==('#'+item.path);
            });
            if(index>=0){
                document.querySelector("#router-view").innerHTML=vue.routes[index].component;
            }else {

                let defaultIndex=vue.routes.findIndex((item,index)=>{
                    return item.path=='*';
                });
                if(defaultIndex>=0){
                    window.location.hash=vue.routes[defaultIndex].redirect;
                }

            }
        };

        vue.init();
    }

    new Vue({
        routes:[
            { path: '/home', component: '<h1>主页</h1><h4>[email protected]</h4>' },
            { path: '/news', component: '<h1>新闻</h1><h4>web-7258</h4>' },
            { path: '/team', component: '<h1>团队</h1><h4>WEB前端梦之蓝</h4>' },
            { path: '/about', component: '<h1>关于</h1><h4>关注公众号:web-7258</h4>' },
            { path:'*', redirect:'/home'}
        ]
    });
</script>
</body>
</html>

更多精彩文章,敬请持续关注——WEB前端梦之蓝

用微信扫描下方的二维码可直接关注该公众号哦,或者打开微信公众号搜索 “web-7258”,关注后会在第一时间将最新文章推送给您哦!

猜你喜欢

转载自blog.csdn.net/u013350495/article/details/83034213