Vue Router activated deactivated 路由守卫

文章介绍了Vue中路由组件的activated和deactivated钩子,用于在组件激活和失活时执行相应操作,如News组件的淡入淡出效果。同时,详细阐述了路由守卫的概念,包括全局守卫、独享守卫和组件内守卫,用于实现路由的权限控制,确保只有授权用户才能访问特定页面。文章还提到了VueRouter的两种工作模式:hash模式和history模式,以及它们的优缺点和应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

6.12.activated deactivated

activateddeactivated是路由组件所独有的两个钩子,用于捕获路由组件的激活状态具体使用

  1. activated路由组件被激活时触发
  2. deactivated路由组件失活时触发

在这里插入图片描述

src/pages/News.vue

<template>
    <ul>
        <li :style="{opacity}">欢迎学习vue</li>
        <li>news001 <input type="text"></li></li>
        <li>news002 <input type="text"></li></li>
        <li>news003 <input type="text"></li></li>
    </ul>
</template>

<script>
    export default {
        name: "News",
        data(){
            return {
                opacity:1
            }
        },
        activated() {
            console.log('News组件被激活了');
            this.timer = setInterval(() => {
                this.opacity -= 0.01;
                if(this.opacity <= 0) this.opacity = 1
            },16)
        },
        deactivated() {
            console.log('News组件失活了');
            clearInterval(this.timer)
        }
    }
</script>

6.13.路由守卫

作用:对路由进行权限控制

分类:全局守卫、独享守卫、组件内守卫 全局守卫

  1. 全局守卫
    1. meta路由源信息
      // 全局前置守卫:初始化时、每次路由切换前执行
      router.beforeEach((to,from,next) => {
        console.log('beforeEach',to,from);
        if(to.meta.isAuth){ // 判断当前路由是否需要进行权限控制
          if(localStorage.getItem('school') === 'atguigu'){ // 权限控制的具体规则
            next(); // 放行
          } else { 
            alert('暂无权限查看');
          }
        } else { 
          next(); // 放行 
        }
      })
      
      // 全局后置守卫:初始化时、每次路由切换后执行
      router.afterEach((to,from) => {
        console.log('afterEach',to,from);
        if(to.meta.title) { 
          document.title = to.meta.title;//修改网页的title 
          } else { 
            document.title = 'vue_test' ;
          }
      })
      
  2. 独享守卫
    beforeEnter(to,from,next){
      console.log('beforeEnter',to,from);
      if(localStorage.getItem('school') === 'atguigu') { 
        next();
      } else { 
        alert('暂无权限查看');
      }
    })
    
  3. 组件内守卫
    //进入守卫:通过路由规则,进入该组件时被调用 
    beforeRouteEnter (to, from, next) {... next()},
    
    //离开守卫:通过路由规则,离开该组件时被调用 
    beforeRouteLeave (to, from, next) {... next()},
    

6.13.1.全局路由守卫

src/router/index.js

import VueRouter from 'vue-router';

// 引入组件
import About from '../pages/About';
import Home from '../pages/Home';
import News from '../pages/News';
import Message from '../pages/Message';
import Detail from '../pages/Detail';

// 创建并暴露一个路由器
const router =  new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About,
            meta:{title:'关于'}
        },
        {
            name:'zhuye',
            path:'/home',
            component:Home,
            meta:{title:'主页'},
            children: [
                {
                    name:'xinwen',
                    path:'news',
                    component:News,
                    meta:{isAuth:true,title:'新闻'}
                },
                {
                    name:'xiaoxi',
                    path:'message',
                    component:Message,
                    meta:{isAuth:true,title:'消息'},
                    children: [
                        {
                            name:'Detail', // name配置项为路由命名
                            path:'detail', // 使用占位符声明接收params参数
                            component:Detail,
                            meta:{isAuth:true,title:'详情'},
                            props($route){ // 这里可以使用解构赋值
                                return {
                                    id: $route.params.id,
                                    title: $route.params.title
                                }
                            }
                        }
                    ]
                }
            ]
        }
    ]
})

// 全局前置路由守卫————初始化的时候、每次路由切换之前被调用
router.beforeEach((to,from,next) => {
    console.log('前置路由守卫',to,from);
    if(to.meta.isAuth){
        if(localStorage.getItem('school')==='atguigu'){
            next();
        } else{
            alert('学校名不对,无权限查看!');
        }
    } else {
        next();
    }
});

// 全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from) => {
    console.log('后置路由守卫',to,from);
    document.title = to.meta.title || '硅谷系统';
});


export  default router;

6.13.2.独享路由守卫

src/router/index.js

import VueRouter from 'vue-router';

// 引入组件
import About from '../pages/About';
import Home from '../pages/Home';
import News from '../pages/News';
import Message from '../pages/Message';
import Detail from '../pages/Detail';

// 创建并暴露一个路由器
const router =  new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About,
            meta:{title:'关于'}
        },
        {
            name:'zhuye',
            path:'/home',
            component:Home,
            meta:{title:'主页'},
            children: [
                {
                    name:'xinwen',
                    path:'news',
                    component:News,
                    meta:{isAuth:true,title:'新闻'},
                    // 🔴独享守卫,特定路由切换之后被调用
                    beforeEnter(to,from,next){
                        console.log('前置路由守卫',to,from);
                        if(to.meta.isAuth){
                            if(localStorage.getItem('school')==='atguigu'){
                                next();
                            } else{
                                alert('学校名不对,无权限查看!');
                            }
                        } else {
                            next();
                        }
                    }
                },
                {
                    name:'xiaoxi',
                    path:'message',
                    component:Message,
                    meta:{isAuth:true,title:'消息'},
                    children: [
                        {
                            name:'Detail', // name配置项为路由命名
                            path:'detail', // 使用占位符声明接收params参数
                            component:Detail,
                            meta:{isAuth:true,title:'详情'},
                            props($route){ // 这里可以使用解构赋值
                                return {
                                    id: $route.params.id,
                                    title: $route.params.title
                                }
                            }
                        }
                    ]
                }
            ]
        }
    ]
})

// 全局前置路由守卫————初始化的时候、每次路由切换之前被调用
// router.beforeEach((to,from,next) => {
//     console.log('前置路由守卫',to,from);
//     if(to.meta.isAuth){
//         if(localStorage.getItem('school')==='atguigu'){
//             next();
//         } else{
//             alert('学校名不对,无权限查看!');
//         }
//     } else {
//         next();
//     }
// });

// 全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
// router.afterEach((to,from) => {
//     console.log('后置路由守卫',to,from);
//     document.title = to.meta.title || '硅谷系统';
// });


export  default router;

6.13.3.组件内路由守卫

src/pages/About.vue

<template>
    <h2>我是About的内容</h2>
</template>

<script>
    export default {
        name: "About",
        // 通过路由规则,进入该组件时被调用
        beforeRouteEnter (to, from, next) {
            console.log('About--beforeRouteEnter', to, from);
            if(localStorage.getItem('school') === 'atguigu') {
                next();
            } else {
                alert('学校名不对,无权限查看!');
            }
        },
        // 通过路由规则,离开该组件时被调用
        beforeRouteLeave (to, from, next) {
            console.log('About--beforeRouteLeave', to, from) ;
            next();
        }
    }
</script>

6.14.路由器的两种工作模式

  1. 对于一个url来说,什么是hash值? #及其后面的内容就是hash值
  2. hash值不会包含在HTTP请求中,即:hash值不会带给服务器
  3. hash模式
    1. 地址中永远带着#号,不美观
    2. 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法
    3. 兼容性较好
  4. history模式
    1. 地址干净,美观
    2. 兼容性和hash模式相比略差
    3. 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题
const router = new VueRouter({ 
  mode:'history', 
  routes:[...] 
})

export default router;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值