Vue3_15(VueRouter)
作者:互联网
前端路由是如何做到URL和内容进行映射呢?监听URL的改变。
URL的hash
URL的hash也就是锚点(#), 本质上是改变window.location的href属性;
可以通过直接赋值location.hash来改变href, 但是页面不发生刷新;
<div id="app"> <a href="#/home">home</a> <a href="#/about">about</a> <div class="content">Default</div> </div> <script> const contentEl = document.querySelector('.content'); window.addEventListener("hashchange", () => { switch(location.hash) { case "#/home": contentEl.innerHTML = "Home"; break; case "#/about": contentEl.innerHTML = "About"; break; default: contentEl.innerHTML = "Default"; } }) </script>
HTML5的History
replaceState:替换原来的路径;
pushState:使用新的路径;
popState:路径的回退;
go:向前或向后改变路径;
forward:向前改变路径;
back:向后改变路径;
<div id="app"> <a href="/home">home</a> <a href="/about">about</a> <div class="content">Default</div> </div> <script> const contentEl = document.querySelector('.content'); const changeContent = () => { switch(location.pathname) { case "/home": contentEl.innerHTML = "Home"; break; case "/about": contentEl.innerHTML = "About"; break; default: contentEl.innerHTML = "Default"; } } const aEls = document.getElementsByTagName("a"); for (let aEl of aEls) { aEl.addEventListener("click", e => { e.preventDefault(); const href = aEl.getAttribute("href"); history.pushState({}, "", href); //history.replaceState({}, "", href); changeContent(); }) } window.addEventListener("popstate", changeContent) </script>
标签:15,contentEl,home,innerHTML,href,location,VueRouter,Vue3,const 来源: https://www.cnblogs.com/hexrui/p/15754274.html