路由监听 路由钩子 全局路由钩子

108 阅读1分钟

路由监听

 watch:{
        // 一
        // $route 路由信息对象  to 目标地址  from 从哪来的
        // $route(to, from) {
        //     console.log(to, from);
        //     this.getList();
        // },

  
        // 二
        $route:{
            immediate: true,
            handler(to, from) {
                this.getList();
            }
        }
    },

路由组件钩子

 // 更新:home 到 about 或者 about 到 home 不会执行的      about/123 到 about/456 才会执行
    beforeRouteUpdate(to, from, next) {
        console.log('beforeRouteUpdate, 路由更新前执行,可以使用this');
        this.getList();
        next();  // 放行  如果不调用,/about/123 无法跳转到 /about/456
    },
 // 进入:从其他路由进入到当前路由之前执行   /about/123 到 /about/456 不会执行  /home 到 /about 才会执行  

    // 比created执行的更早
    beforeRouteEnter(to, from, next) {
        console.log('beforeRouteEnter', this);  // 无法访问this

        next();

        // next((vm) => {  // vm相当于是this
        //     console.log(vm);
        // })

    },
 beforeRouteLeave(to, from, next) {
        console.log('beforeRouteLeave, 路由离开之前执行',to.path);
        next();
    }

全局路由钩子

  {
    path: '/about/:id',
    name: 'about',
    component: () => import('../views/About.vue'),
    meta:{
      title:'about',
      login:true,
    },
  },

  {
    path:'/login',
    name:'login',
    components:{
      default:()=>import('../views/login.vue'),
    },
    meta:{
      title:'登录',
      login:false,
    },
 router.beforeEach((to,from,next)=>{
    console.log(1);
    document.title=to.meta.title;

  
    //不需要登陆的页面 可设置meta属性的自定义状态判断
    if (!to.meta.login) {
        next();
        return;
    }

  
    // 需要登录,判断是否具有token
    if (!localStorage.Token) {
        next(`/login?path=${to.fullPath}`);
        return;
    }

    // 已登录
    next();

})