js实现简单前端路由--hash方式

在单页面应用程序(SPA)中,前端通过url的改变来渲染不同的页面, 但希望能将url的页面记录下来。这样可以使用浏览器的后退前进键来返回上一页。

要实现这一点,首先要实现前端路由。根据路由的不同,渲染不同页面,执行不同方法。

简单的前端路由有两种实现方式:

1. hash

2.history API

//------------------------------------------------------------------------------------------------

下面介绍第一种hash的方式。

这一方式,主要是通过监听onhashchange事件来实现的,但是有浏览器兼容性问题。下面是浏览器支持的情况(截图来源:http://www.runoob.com/jsref/event-onhashchange.html)。


在不支持此事件的浏览器中,可以通过轮询hash是否变化来实现。

下面是实现了简单前端路由功能的一个小demo。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .content{
            position:absolute;
            left: 0px;
            top:0px;
            display: none;
        }
    </style>
</head>
<body>
    <div id="index-page" class="content">
        <ul>
            <li><a href="#/index">index</a></li>
            <li><a href="#/text">text</a></li>
            <li><a href="#/news">news</a></li>
            <li><a href="#/about">about</a></li>
            <li><a href="http://www.baidu.com">baidu</a></li>
        </ul>
    </div>
    <div id="text-page" class="content">
        <h1> this is text page</h1>
        <a href="#/index">back</a>
    </div>
    <div id="news-page" class="content">
        <h1>this is new page</h1>
        <a href="#/index">back</a>
    </div>
    <div id="about-page" class="content">
        <h1>this is about page</h1>
        <a href="#/index">back</a>
    </div>
    <script>
        //构造函数
        function Router(){
            this.routes={};
            this.currentURL='';
        }
        //定义路由回调函数
        Router.prototype.route = function(path,callback){
            this.routes[path] = callback || function(){};
        }
        //定义路由更新时的调用函数
        Router.prototype.refresh = function(){
            this.currentURL = location.hash.slice(1) || '/index';
            try {  //抛出路由不正确的路由
                this.routes[this.currentURL]();
            }
            catch(err) {
                alert("请输入合法路由");
            }
        }
        //路由初始化函数,添加监听事件
        Router.prototype.init = function () {
            var that = this;
            if (window.addEventListener) { 
                window.addEventListener("load",function(){that.refresh();},false);
                if ( "onhashchange" in window.document.body ) { 
                    window.addEventListener("hashchange",function(){that.refresh();},false)  
                }else{
                    onhashchange_compatibility(that);
                }
            } else if (window.attachEvent) { //ie低版本兼容
                window.attachEvent("onload",function(){that.refresh();},false);
                window.attachEvent("onhashchange",function(){that.refresh();},false)
                onhashchange_compatibility(that);
            }  
            //bind()函数IE8以下不支持
            // window.addEventListener('load',this.refresh.bind(this),false);
            // window.addEventListener('hashchange',this.refresh.bind(this),false);
        }

        //轮询url的变化
        function onhashchange_compatibility(that){
            var location = window.location,
            oldURL = location.href,
            oldHash = location.hash;
            // 每隔100ms检查hash是否发生变化
            setInterval(function() {
                var newHash = location.hash;
                if ( newHash != oldHash) {
                    that.refresh();
                    oldURL = location.href;
                    oldHash = newHash;
                }
            }, 100);
        }

        //自定义路由更新时的回调函数
        function display_page(id){
            var el = document.getElementsByClassName("content");
            for(var i = 0; i < el.length; i++){
                el[i].style.display = "none";
            }         
            el[id].style.display = "block";
        }
         
        window.Router = new Router();
        //将合法路由以及执行的回调函数写入routes
        Router.route('/index',function(){
            display_page(0);
        })
        Router.route('/text',function(){
            display_page(1);
        })
        Router.route('/news',function(){
            display_page(2);
        })         
        Router.route('/about',function(){
            display_page(3);
        })
        //初始化
        window.Router.init();
    </script>
</body>
</html>

//叨叨-----------------------------------------------------------------------------------

这是我的学习笔记,参考网上的博文写的代码,网址找不到了,所以没贴出来。

每挖一个坑,会发现里面超级深,初入门,请多指教。


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue Router 是 Vue.js 官方的路由管理器,用于实现前端路由跳转。要进行路由跳转,你需要完成以下几个步骤: 1. 首先,确保你的项目中已经安装了 Vue Router。可以通过 npm 或 yarn 进行安装: ```bash npm install vue-router ``` 或 ```bash yarn add vue-router ``` 2. 在你的 Vue 项目的入口文件(一般是 `main.js`)中引入 Vue Router,并使用它: ```javascript import Vue from 'vue' import VueRouter from 'vue-router' // 导入你的路由配置文件 import routes from './routes' Vue.use(VueRouter) const router = new VueRouter({ mode: 'history', // 可选值为 'hash' 或 'history',默认为 'hash' routes // 路由配置 }) new Vue({ router, // 注入路由实例 render: h => h(App) }).$mount('#app') ``` 3. 创建一个路由配置文件(例如 `routes.js`),在该文件中定义路由的映射关系: ```javascript import Home from './views/Home.vue' import About from './views/About.vue' const routes = [ { path: '/', name: 'home', component: Home }, { path: '/about', name: 'about', component: About } ] export default routes ``` 4. 在你的 Vue 组件中使用 `<router-link>` 标签或 `$router` 对象进行路由跳转。下面是几个常用的示例: - 使用 `<router-link>` 标签实现路由跳转: ```html <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> ``` - 使用 `$router` 对象编程式地进行路由跳转: ```javascript // 在某个方法中跳转到指定路由 this.$router.push('/') // 跳转到根路径 this.$router.push('/about') // 跳转到 /about 路径 // 在某个方法中通过路由名称跳转 this.$router.push({ name: 'home' }) // 跳转到名称为 home 的路由 ``` 这样,你就可以通过 Vue Router 实现路由跳转了。请注意,以上只是一个简单的示例,你可以根据实际需要配置更多高级功能,例如路由参数、嵌套路由等。详情请参考 Vue Router 的官方文档。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值