hash
: 使用 URL hash 值来作路由。支持所有浏览器,包括不支持 HTML5 History Api 的浏览器。
document.addEventListener('DOMContentLoaded', function () {
console.log(location.hash);
})
window.addEventListener('hashchange', function (event) {
const { newURL, oldURL } = event
console.log('listen', newURL, oldURL, event)
const newHash = newURL.split('#').pop()
document.getElementById('app').innerHTML = newHash
})
function routeTo (targetName) {
console.log('click', targetName)
location.hash = targetName
}
history
: 依赖 HTML5 History API 和服务器配置。查看 HTML5 History 模式。
document.addEventListener('DOMContentLoaded', function () {
console.log(location.pathname);
})
window.addEventListener('popstate', function (event) {
var { state } = event
console.log('listen', state, event)
changeView(JSON.stringify(state))
})
function routeTo (targetName) {
console.log('click', targetName)
push(targetName)
}
function push (targetName) {
var state = { page_name: targetName };
var title = '';
var url=`${targetName}.html`;
history.pushState(state, title, url)
changeView(targetName)
}
function replace(targetName) {
var state = { page_name: targetName };
var title = '';
var url=`${targetName}.html`;
history.replaceState(state, title, url)
changeView(targetName)
}
function changeView(val) {
document.getElementById('app').innerHTML = val
}
abstract
: 支持所有 JavaScript 运行环境,如 Node.js 服务器端。如果发现没有浏览器的 API,路由会自动强制进入这个模式。
代码:https://gitee.com/daaasheng/whiteboard/tree/master/vue-router/mode