直接上代码
在页面上写点东西
<p><a href="#/home">首页
</a>|
<a href="#/about">关于
</a>|
<a href="#/info">信息
</a></p>
<div id="home">
<h1>首页
</h1>
</div>
<div id="about">
<h1>关于
</h1>
</div>
<div id="info">
<h1>信息
</h1>
</div>
默认显示第一个,也就是首页
<style>
#about {
display: none;
}
#info {
display: none;
}
</style>
看一下页面效果现在需要实现需求,点击关于页面显示关于,同时URL也显示对应的a标签href的内容
通过hashchange改变事件来实现这个需求hash就是页面上显示URL一大堆if判断就是让对应的文字显示没有用document.getElementById是因为,当元素为页面唯一元素的时候可以直接用
window
.onhashchange = function (e
) {
let hash
= window
.location
.hash
;
console
.log(hash
)
if (hash
== '#/home') {
home
.style
.display
= 'block';
about
.style
.display
= 'none';
info
.style
.display
= 'none';
} else if (hash
== '#/about') {
home
.style
.display
= 'none';
about
.style
.display
= 'block';
info
.style
.display
= 'none';
} else if (hash
== '#/info') {
home
.style
.display
= 'none';
about
.style
.display
= 'none';
info
.style
.display
= 'block';
}
}
看一下打印出来的hash
看一下页面效果
Vue路由跳转(正戏)
是不是感觉很熟悉?这就是vue的路由配置方式path是地址栏显示的URLcomponent是需要显示对用的页面,在这里就是那几个div
const router
= [
{path
:'#/home',component
:home
},
{path
:'#/about',component
:about
},
{path
:'#/info',component
:info
}
]
对应的js代码
let currentView
= router
[0];
window
.onhashchange = function(e
) {
for(let i
= 0; i
< router
.length
; i
++) {
if(location
.hash
== router
[i
].path
) {
currentView
.component
.style
.display
= 'none';
router
[i
].component
.style
.display
= 'block';
currentView
= router
[i
];
break;
}
}
}
看一下效果是否一样