只是實(shí)現(xiàn)了跳轉(zhuǎn),關(guān)于vue-router的一些參數(shù)懶加載沒有嗷~
hash模式的html元素:
<div>
<a href="#/home">跳轉(zhuǎn)到首頁</a>
<a href="#/mine">跳轉(zhuǎn)到我的</a>
<a href="#/list">跳轉(zhuǎn)到列表</a>
</div>
<div id="box"></div>
hash模式的js:
var box = document.getElementById('box')
var router = [
{
path:'/home',
text:'首頁的組件'
},
{
path:'/mine',
text:'我的信息的組件'
},
{
path:'/list',
text:'列表的組件'
},
]
// hash模式的路由
window.addEventListener('hashchange',function(){
console.dir(location.hash)
var hashPath = location.hash
// 找出存在router的path
var component = router.find(h=> '#'+h.path===hashPath)
if(component){// 存在就賦值
box.innerHTML = component.text
}else{
box.innerHTML = '404'
}
})
history模式
html中將href的#去掉
js中router保持不變,監(jiān)聽如下:
var aList = document.querySelectorAll('a')
aList.forEach(a => {
a.addEventListener('click',function(e){
// 阻止a的默認(rèn)跳轉(zhuǎn)事件
e.preventDefault()
// 往瀏覽器記錄加一個(gè)記錄
history.pushState({username:'zy'},'',e.target.href)
console.dir(location)
var hashName = location.pathname
// 找出存在router的path
var component = router.find(h=> h.path===hashName)
if(component){
box.innerHTML = component.text
}else{
box.innerHTML = '404'
}
})
});
測(cè)試方法:
vscode Live Server插件服務(wù)運(yùn)行index.html文件
右鍵選擇open with live server運(yùn)行
運(yùn)行地址http://127.0.0.1:5500/