欢迎使用CSDN-markdown编辑器

来源:互联网 发布:2017 博士 知乎 编辑:程序博客网 时间:2024/06/07 01:35
这里我们使用Vue-ruter的设置思想制造一个简单的路由

其他的就是vue本身的一些方法了具体的自己脑补一下vue
js主入口文件里需要使用h5新的特性即history
下面首先介绍一下window.history的一些常用的东东
以前我们知道经常使用的是在他的proto上继承的back,forward,go的函数
这样的弊端就是,我们只能操作前进后退,但是无法控制前进后退要到的地方,history.length都只会维持原来的状态。。
下面就是我们的主角了
html5新的api扩展了window.history,可以存储当期啊你是记录点pushState,替换当前历史记录点repleaceState,监听历史记录点popstate
其中pushState和repleaceState的用法差不多
history.pushState(data,title,url)
//其中第一个参数data是给state的值;第二个参数title为页面的标题,但当前所有浏览器都忽略这个参数,传个空字符串就好;第三个参数url是你想要去的链接;

replaceState用法类似

两者区别:pushState会改变history.length,而replaceState不改变history.length
下面一个简单的例子说明区别

<!DOCTYPE html><html><head>    <meta charset="utf-8">    <title>windowHistory</title></head><body>   <span class="js-news">新闻</span>  <span class="js-music">音乐</span>  <script type="text/javascript">    var locationHref = location.href;    // document.addEventListener("click", function (event) {    //     var target = event.target;    //     if (target.className == "js-news") {    //         history.pushState("首页", "", locationHref + "#news");    //     } else if (target.className == "js-music") {    //         history.pushState("音乐", "", locationHref + "#music");    //     }    // });     document.addEventListener("click",function(event){     var target = event.target;     if(target.className == "js-news"){     history.replaceState("首页","",locationHref + "#news");     }else if(target.className == "js-music"){     history.replaceState("音乐","",locationHref + "#music");     }     });    window.addEventListener("popstate", function () {        console.log(history.state);    })  </script></body></html>这里写代码片`览器状态(popstate)变化事件可以理解为监听浏览器后退、前进的操作,只要后退或者前进就会触发

具体的实现可以github

0 0
原创粉丝点击