1. 程式人生 > >Vue之路由裡的鉤子函式

Vue之路由裡的鉤子函式

  • 在router.js裡定義鉤子函式

在router.js裡新增beforeEnter和beforeLeave這兩個鉤子函式,beforeEnter這個鉤子函式需要新增next();不然頁面不能進行跳轉;beforeLeave鉤子函式在router.js是失效的,需要在元件裡定義: 鉤子函式的三個引數:

to:router即將進入的路由物件
from:當前導航即將離開的路由
next:Function,進行管道中的一個鉤子,如果執行完了,則導航的狀態就是 confirmed (確認的);
否則為false,終止導航。
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Error from './views/Error.vue'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: "/",
      redirect: '/home'
    },
    {
      path: '/home',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/About.vue'),
      beforeEnter: (to,from,next) => {
        console.log(to);
        console.log(from);
        console.log(next);
        // 閘門的作用 不加的話,頁面不能進行調整 false:關 true:開
        //next() :開
        next(true)
      }, 
       beforeLeave: (to,from,next) => {
        console.log(to);
        console.log(from);
        console.log(next);
        next(false)
      }, 
    },
    {
      path: '*',
      name: 'error',
      component: Error
    },
  ]
})

  • 在元件裡定義鉤子函式
<script>
export default {
  data(){
    return{
    }
  },
  beforeRouteEnter: (to,from,next) => {
    console.log("進入about之前");
    next(true)
  },
  beforeRouteLeave: (to,from,next) => {
    console.log("離開about之前");
    next(true)
  },
}
</script>