一、锚点的哈希路由
1.相关知识点:
location.hash
:获取url中的锚点地址hashchange
:url锚点改变事件- 通过监听url路径中描点值的变化来改变视图中显示的内容
2.代码演示
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>基于锚点的哈希路由</title>
</head>
<body>
<nav>
<a href="#tupian1">图片1</a>
<a href="#tupian2">图片2</a>
</nav>
<div class="route-view">
</div>
</body>
<script>
let view=document.querySelector(".route-view");
window.addEventListener("hashchange",show);
function show(){
console.log(location.hash);
switch(location.hash.trim()){
case "#tupian1":
view.innerHTML="<h1>图片1</h1>"
break;
case "#tupian2":
view.innerHTML="<h1>图片2</h1>"
break;
default:
view.innerHTML="图片"
}
}
window.addEventListener("load",show);
</script>
</html>
二、Vue路由
1.相关知识点
- vue路由的使用:文档需要加载vue-router.js和vue.js
下载地址:https://unpkg.com/vue-router@3.4.9/dist/vue-router.js
- Vue使用的相关组成
- 视图组成:
<router-link to="/path"></router-link>
标签组成路由链接,其to属性路由路径;<rotuer-view></rotuer-view>
路由内容显示区域 - JS代码:通过new VueRouter({})路由对象实列,挂在到new Vue()实例的router上
- 常见的VueRouter实列对象常有:
- 视图组成:
const router=new VueRouter({
routes:[
{path:"/",redirect:"/part1"},//设置默认展示的路由页面
{path:"/part1",component:part1},
{path:"/part2",component:part2},
],
linkActiveClass:"red",
})
2.代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vue路由入门</title>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<script src="vue-router.js" type="text/javascript" charset="utf-8"></script>
<style>
.red{
color:red;
}
</style>
</head>
<body>
<div class="app">
<router-link to="/part1">国内新闻</router-link>
<router-link to="/part2">国际新闻</router-link>
<router-view></router-view>
</div>
</body>
<script>
let part1={
template:`<ul><li>国内one</li><li>国内two</li><li>国内three</li></ul>`
}
let part2={
template:`<ol><li>国际one</li><li>国际two</li><li>国际three</li></ol>`
}
const router=new VueRouter({
routes:[
{path:"/",redirect:"/part1"},//设置默认展示的路由页面
{path:"/part1",component:part1},
{path:"/part2",component:part2},
],
linkActiveClass:"red",//激活的样式
})
new Vue({
el:".app",
router:router,
})
</script>
</html>
3.展示结果
H5中history属性相关知识
1.history.pushState(null,"",link.href)
:把获得的href值push到url中
2.popstate
:事件,监听url的改变
3.location.pathname
:获取当前url中的值