對vue中鈎子函數的理解


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();
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM