马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Hash 模式
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <nav class="nav-box">
- <a href="#/">首页</a>
- <a href="#/about">关于</a>
- <a href="#/product">产品</a>
- </nav>
- <div id="app"></div>
- <script>
- const app = document.querySelector('#app')
- const navBox = document.querySelector('.nav-box')
- const routes = [
- {
- path: '/',
- component: '组件-首页home' // 应是组件
- },
- {
- path: '/about',
- component: '组件-关于我们'
- },
- {
- path: '/product',
- component: '组件-产品列表'
- }
- ]
-
- const routeMatch = () => {
- const hash = location.hash.substring(1) // 去掉hash的 #
- let text = ''
- routes.forEach(it => {
- if(it.path === hash) text = it.component
- })
- app.innerHTML = text
- }
- // 首次渲染 /
- location.hash = '/'
- routeMatch()
- // 监听 hash 变化
- window.onhashchange = routeMatch
- </script>
- </body>
- </html>
复制代码 H5的history模式
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <nav class="nav-box">
- <a href="/">首页</a>
- <a href="/about">关于</a>
- <a href="/product">产品</a>
- </nav>
- <div id="app"></div>
- <script>
- const app = document.querySelector('#app')
- const navBox = document.querySelector('.nav-box')
- const routes = [
- {
- path: '/',
- component: '组件-首页home' // 应是组件
- },
- {
- path: '/about',
- component: '组件-关于我们'
- },
- {
- path: '/product',
- component: '组件-产品列表'
- }
- ]
-
- // 事件委托,点击事件
- navBox.onclick = (event) => {
- if(event.target.tagName === 'A') {
- event.preventDefault() // 阻止默认事件,跳转并刷新
- // Failed to execute 'pushState' on 'History': A history state object with URL ' cannot be created in a document with origin 'null' and URL '
- history.pushState({}, '', event.target.href)
- routeMatch()
- }
- }
- const routeMatch = () => {
- const pathname = location.pathname
- let text = ''
- routes.forEach(it => {
- if(it.path === pathname) text = it.component
- })
- app.innerHTML = text
- }
- // 首次渲染 /
- history.pushState(null, '', '/')
- routeMatch()
- // 监听popstate地址变化事件; 执行go/forward/back等方法可以触发
- window.onpopstate = routeMatch
- </script>
- </body>
- </html>
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |