1、beforeCreate 钩子
该阶段组件实例刚创建,组件属性计算之前(可理解为组件属性还未初始化,未绑定,未挂载元素el),比如:el,data,methods等,如果你试图在beforeCreated钩子中获取这些属性值,会得到ubdefined 的结果,但是
可以获取到this对象,因为此时组件刚被创建好,所以this已经引用了该组件对象。
2、created 钩子
该阶段组件实例创建完成,组件属性绑定完成,但DOM还未生成,el属性还不存在
3、beforeMount 钩子
该阶段组件实例已经创建完成,但是el还未挂载具体元素
4、mounted钩子
该阶段组件实例已经创建完成,但是el 已挂载具体元素,此时的el属性不为undefined
5、Vue:router 的beforeEach 与afterEach 钩子函数
在路由跳转的时候,我们需要一些权限判断或者其他操作。这个时候就需要使用路由的钩子函数。
定义:路由钩子主要是给使用者在路由发生变化时进行一些特殊处理而定义的函数
总体来说,vue里面提供了三大类钩子,两种函数
1、全局钩子
2、某个路由的钩子
3、组件内钩子
两种函数:
1、Vue.beforeEach(function(to,from,next){}) // 在跳转之前执行
2、Vue.afterEach(function(to,from){}) // 在跳转之后判断
全局钩子函数
顾名思义,它是对全局有效的一个函数
router.beforeEach((to,from,next)=>{
let token = router.app.$storage.fetch("token");
let needAuth = to.matched.some(item => item.meta.login);
if(!token && needAuth) return next({path: "/login"});
next();
})
beforeEach 函数有三个参数:
to: router 即将进入路由对象
from:当前导航即将离开的路由
next:Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是confirmed(确认的);否则为false,终止导航
afterEach 函数不用传next()函数
某个路由的钩子函数
顾名思义,它是写在某个路由里头的函数,本质上跟组件内函数没有区别
const router = new VueRouter({ routes: [ { path: '/login', component: Login, beforeEnter: (to, from, next) => { // ... }, beforeLeave: (to, from, next) => { // ... } } ] })
路由组件的钩子
注意:这里说的是路由组件!
路由组件 属于 组件,但组件 不等同于 路由组件!所谓的路由组件:直接定义在router中component处的组件。如:
var routes = [
{
path:'/home',
component:home,
name:"home"
}
]
用 vue-route 的 beforeEach 实现导航守卫(路由跳转前验证登录)
下面写一个例子,需要在跳转前判断是不是已登录;已登录的情况再去登录页,跳转至首页:
const vueRouter = new Router({
routes: [
//......
{
path: '/account',
name: 'account',
component: Account,
children: [
{name: 'course', path: 'course', component: CourseList},
{name: 'order', path: 'order', component: OrderList}
]
}
]
});
vueRouter.beforeEach(function (to, from, next) {
const nextRoute = [ 'account', 'order', 'course'];
const auth = store.state.auth;
//跳转至上述3个页面
if (nextRoute.indexOf(to.name) >= 0) {
//未登录
if (!store.state.auth.IsLogin) {
vueRouter.push({name: 'login'})
}
}
//已登录的情况再去登录页,跳转至首页
if (to.name === 'login') {
if (auth.IsLogin) {
vueRouter.push({name: 'home'});
}
}
next();
});