我们知道一个组件从进入到销毁有很多的钩子函数,同样在路由中也设置了钩子函数。路由的钩子选项可以写在路由配置文件中,也可以写在我们的组件模板中。
一.路由配置文件中的钩子函数
/src/router/index.js
路由文件中我们只能写一个beforeEnter,就是在进入此路由配置时。
{
path:'/params/:newsId(\\d+)/:newsTitle',
component:Params,
beforeEnter:(to,from,next)=>{
console.log('我进入了params模板');
console.log(to);
console.log(from);
next();
},
三个参数:
to
:路由将要跳转的路径信息,信息是包含在对像里边的。from
:路径跳转前的路径信息,也是一个对象的形式。next
:路由的控制参数,常用的有next(true)和next(false)
二.写在模板中的钩子函数
两个钩子函数可以使用:
- beforeRouteEnter:在路由进入前的钩子函数。
- beforeRouteLeave:在路由离开前的钩子函数。
export default {
name: 'params',
data () {
return {
msg: 'params page'
}
},
beforeRouteEnter:(to,from,next)=>{
console.log("准备进入路由模板");
next();
},
beforeRouteLeave: (to, from, next) => {
console.log("准备离开路由模板");
next();
}
}
</script>
ps:路由钩子函数先于vuex执行 => 若要用this.$store.必须要局部单个页面import vuex