<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>我的路由</title>
</head>
<body>
<a href="#/home">HOME</a>
<a href="#/cart">CART</a>
<p>哈哈</p>
<router-view></router-view>
<div>
嘻嘻
</div>
</body>
</html>
<script>
// 根據位址列錨值的沒同在router-view位置顯示不同的內容
var Home = {template: '<div>我是Home</div>'}
var Cart = {template: '<div>我是Cart</div>'}
var routes = [
{name:'home',path:'/home',component:Home},
{name:'cart',path:'/cart',component:Cart}
]
// 1.監聽位址列錨點改變的事件hashchange
window.onhashchange = function () {
console.log('只要錨變化,就會執行這個方法')
// 2.要判斷當前位址列中錨點值是什麼
// 如果當前的錨點值與我們寫的規則中的routes對應,就顯示相應的component
var hash = location.hash // #/xxx
// splice
hash = hash.slice(1, hash.length)
// 3.遍歷routes,去判斷每個元素的path 是否與hash相等
for (var i = 0; i < routes.length; i++) {
var item = routes[i]
if(item.path === hash){
// 當相等時,就把當前元素的component屬性的對應的內容插入到頁面
// router-view
var oView = document.querySelector('router-view')
oView.innerHTML = item.component.template
}
}
}
</script>