前端路由实现 (hash、history模式)
一、前端路由
前端路由是指,不同的url展示不同的页面。
前端路由的模式分为两种:
- hash模式:
http://localhost/Day/hash.html#/home
存在一个 # 符号,和普通的url相比有些丑 - history模式:
http://localhost/home
这和普通的URL没有区别,非常好看
那么这两种模式的实现原理是什么呢?
二、hash模式
主要使用:window.location.hash 和 onhashchange() 来实现的;
实现的代码如下:需要在Apach服务下运行。
<!DOCTYPE html>
<html lang="en">
<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>hash</title>
</head>
<body>
<button class="router" to="/home">首页</button>
<button class="router" to="/content">内容</button>
<div class="router-view">
</div>
<script>
var btn=document.getElementsByClassName("router");
var view=document.getElementsByClassName("router-view")[0];
routes=[
{
"path":"/home", "component":"<p>我是首页的组件</p>"},
{
"path":"/content", "component":"<p>我是内容的组件</p>"}
]
// hash值发生改变,组件显示也会改变
for(var i=0;i<btn.length;i++){
btn[i].onclick=function(){
var hash=this.getAttribute("to"); //getAttribute返回指定属性名的属性值
// console.log(hash);
renderView(hash);