vue学习-组件生命周期、路由守卫

组件生命周期

router中加入以下路径

 {
    path:"/life",
    name:"life",
    component: () => import(/* webpackChunkName: "about" */ '../views/Life.vue')

  }

life.vue

<template>
  <div>
    生命周期举例子
  </div>
</template>

<script>
    export default{
        beforeCreate(){
            console.log(" beforeCreate")
        },
        created(){
            console.log("created")
        },
        beforeMount(){
            console.log("挂载之前")
        },
        mounted(){
            console.log("挂载之后")
        },
        beforeUpdate(){
            console.log("更新之前")
        },
        updated(){
            console.log("更新之后")
        },
        beforeDestroy(){
            console.log("销毁之前")
        },
        destroyed(){
            console.log("销毁之后")
        }
        
    }
</script>

进入之后再切换到其他组件:
在这里插入图片描述

路由守卫

1、每次跳转的判断操作

//路由守卫,时间节点
//每次跳转前触发
router.beforeEach((to,from,next)=>{
  console.log("每次跳转前触发")
  //需不需要继续跳转
  console.log(to)
  console.log(from)
  if(to.path=='/life'){
    next('/nopage');
  }else{
    next();
  }
})

//跳转之后触发
router.afterEach((to,from)=>{
  console.log('跳转之后触发')
})

to和from有相应信息
在这里插入图片描述

2、在router配置里单独进行判断

  {
    path:"/luyou",
    name:"luyou",
    component: () => import(/* webpackChunkName: "about" */ '../views/luyou.vue'),
    beforeEnter(to,from,next){
     console.log('单独在路由页面进入之前');
     next();
   }

3、在组件中进行操作

    export default{
        beforeRouteEnter(to,from,next){
             console.log("组件路由进入之前")
             next()
        },
        beforeRouteUpdate(to,from,next){
            console.log("组件路由更新之前");
            next();
        },
        beforeRouteLeave(to,from,next){
            console.log("组件路由离开之前");
            next();
        }
    }
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值