一、beforeCreate 钩子html
该阶段组件实例刚建立,组件属性计算以前(可理解为组件属性还未初始化,未绑定,未挂载元素el),好比:el,data,methods等,若是你试图在beforeCreated钩子中获取这些属性值,会获得ubdefined 的结果,可是vue
能够获取到this对象,由于此时组件刚被建立好,因此this已经引用了该组件对象。app
二、created 钩子函数
该阶段组件实例建立完成,组件属性绑定完成,但DOM还未生成,el属性还不存在fetch
三、beforeMount 钩子this
该阶段组件实例已经建立完成,可是el还未挂载具体元素spa
四、mounted钩子code
该阶段组件实例已经建立完成,可是el 已挂载具体元素,此时的el属性不为undefinedcomponent
五、Vue:router 的beforeEach 与afterEach 钩子函数router
在路由跳转的时候,咱们须要一些权限判断或者其余操做。这个时候就须要使用路由的钩子函数。
定义:路由钩子主要是给使用者在路由发生变化时进行一些特殊处理而定义的函数
整体来讲,vue里面提供了三大类钩子,两种函数
一、全局钩子
二、某个路由的钩子
三、组件内钩子
两种函数:
一、Vue.beforeEach(function(to,from,next){}) // 在跳转以前执行
二、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"
}
]
下面写一个例子,须要在跳转前判断是否是已登陆;已登陆的状况再去登陆页,跳转至首页:
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();});