vue路由模式
vue路由有两种模式,hash和history,默认为hash模式
hash:
URL地址中带有‘#’,如http://www.nihao.com/#/home, hash 的值为#/home,它的特点在于:hash 虽然出现URL中,但不会被包含在HTTP请求中,对后端完全没有影响,因此改变hash不会重新加载页面。
原理:onhashchange事件,可以在window
对象上监听这个事件
const router = new VueRouter({
mode: 'hash',
// 路由规则
routes:[
{
path: '/',
name: 'home',
component: Home
}
]
})
export default rputer
window.onhashchange() = function(event) {
console.log(event.oldURL, event.newURL)
let hash = location.hash.slice(1)
document.body.style.color = hash
}
这个例子是改变页面的字体颜色,hash模式原理大概就是如此;当hash值变化时,就是路由变化时,浏览器会记录下来,从而浏览器的前进后退都可以了,而且页面