hash模式主要是onhashChange事件监听url上#后面(锚点)的改变,控制页面的改变
<body>
<a href="#/home">go Home</a>
<a href="#/about">go about</a>
<a href="#/404">go about</a>
<div id="router-view"></div>
<script>
const routes = [{
path: '/home',
component: '<div>This is Home</div>'
},
{
path: '/about',
component: '<div>This is about</div>'
},
]
function renderCom(path) {
const newRoute = routes.filter(item => {
return item.path === path
})
document.getElementById('router-view').innerHTML = newRoute[0] ? newRoute[0].component : ''
}
// 处理刷新
console.log(window.location.href);
let firstHref = window.location.href
let firstPath = firstHref.substring(
firstHref.indexOf('#/') + 1
)
if (firstPath) {
console.log('进来');
renderCom(firstPath)
}
window.onhashchange = function (ev) {
console.log(ev);
let newPath = ev.newURL.substring(
ev.newURL.indexOf('#/') + 1
)
console.log(newPath);
renderCom(newPath)
}
</script>
</body>
history模式通过HTML5中的两个API,history的pushState和popState方法修改url但不触发页面的跳转,url的改变会触发popState事件,监听该事件也可以实现根据不同的url渲染对应的页面内容
但是因为没有#会导致用户在刷新页面的时候,还会发送请求到服务端,为避免这种情况,需要每次url改变的时候,都将所有的路由重新定位到跟路由下
<body>
<a href="javascript:pageTo('/home')">go Home</a>
<a href="javascript:pageTo('/about')">go about</a>
<a href="javascript:pageTo('/home')">go about</a>
<div id="router-view"></div>
<script>
const routes = [{
path: '/home',
component: '<div>This is Home</div>'
},
{
path: '/about',
component: '<div>This is about</div>'
},
]
function renderCom(path) {
alert(path)
const newRoute = routes.filter(item => {
return item.path === path
})
document.getElementById('router-view').innerHTML = newRoute[0] ? newRoute[0].component : ''
}
function pageTo(path) {
console.log(path);
//history模式利用pushState重写页面的URL,但是不触发页面的跳转
history.pushState({},'标题',path)
renderCom(path)
}
window.addEventListener("popState", function (e) {
console.log('555',e);
alert(e)
})
</script>
</body>
history模式通过http-server插件本地服务测试,
npm install http-server -g
http-server -c-1 (只输入http-server的话,更新了代码后,页面不会同步更新)