vue路由模式
vue路由有两种模式,hash
和history
,默认为hash
模式
hash:
URL地址中带有‘#’,如http:localhost:8080/#/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模式又叫前端路由
history:
URL地址是正常地址,如:http:localhsot:8080/home
,看起来更美观了。利用了HTML5 History Interface
中的 pushState()
和replaceState()
方法,改变路由模式的方法
const router = new VueRouter({
mode: 'history',
// 路由规则
routes:[
{
path: '/',
name: 'home',
component: Home
}
]
})
export default rputer
连个方法用于改变地址栏url,改变地址栏而不跳转,都接收三个参数
参数1:描述当前跳转的信息,为空即可
参数2:title,一般浏览器用不着
参数3:选填url
history还包括back、forward、go
三个方法,对应浏览器的前进,后退,跳转操作。history在切换路由是真正的改变了url地址,所以要后端配合好地址设置,或者利用nginx配置重定向。
history.pushState({color:'green'}, 'green', 'green') // 通过pushstate把页面的状态保存在state对象中
window.onpopstate = function(event) { // 当活动历史记录条目更改时,将触发popstate事件。
console.log(event.state)
if(event.state && event.state.color === 'green'){
document.body.style.color = 'green'
}
}
// nginx
location / {
try_files $uri $uri/ /index.html;
}
路由钩子:
vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的
全局钩子:
beforeEach:
全局前置守卫,所有路由跳转前调用
router.beforeEach((to, from, next) => {
/*
* to:进入到哪个路由去 from:从哪个路由离开 next:路由的控制参数,常用的有next(true)和
next(false)
*/
next() // 正常跳转,不写的话不会跳转
})
afterEach:
全局后置守卫,所有路由跳转后调用
router.afterEach((to, from) => { // 路由跳转后改变一些属性
/*
* to:进入到哪个路由去 from:从哪个路由离开
*/
if (to.meta.title) {
window.document.title = to.meta.title
} else {
window.document.title = '默认的title'
}
})
beforeResolve:
全局解析守卫, router.beforeResolve
和 router.beforeEach
类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。在beforeEach和组件内beforeRouterEnter之后;
单个钩子函数
beforeEnter
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
/*
* to:进入到哪个路由去 from:从哪个路由离开 next:路由的控制参数,常用的有
next(true)和
next(false)
*/
// ...
}
}
]
})
组件级钩子函数
beforeRouter:
这个钩子比生命周期beforeCreated先执行,所以this实例还未创建,不过,你可以通过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。
beforeRouteEnter(to, from, next) {
next((vm) = > {
vm.text = '改变了'
})
}
beforeRouterUpdate:
可以解决二级导航页面只渲染一次的问题,也就是导航是否更新,是否需要更新
beforeRouteUpdate (to, from, next) {
// 这个时候this已经实例了
this.name = to.params.name
next()
}
beforeRouteLeave:
当离开组件是是否允许,这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false)
来取消
beforeRouteLeave (to, from, next) {
const answer = window.confirm('你真的想离开吗?您有未保存的更改!')
if (answer) {
next()
} else {
next(false)
}
}