Vue_路由_query参数_params参数_命名路由_props配置_编程式路由导航_缓存路由组件_新的生命周期钩子_全局、独享、组件内路由守卫_路由的两种工作模式

一、路由概述

一个路由就是一组key:value的对应关系(key为路径,value可能是functioncomponent

前端路由:(valuecomponent)用于展示页面内容,当浏览器的路径改变时,对应的组件就会显示。

多个路由需要经过路由器的管理

router包含多个route规则(/class => 班级组件 、/subject => 学科组件)

vue-router 专门用来实现SPA应用

注: SPA页面(单页面应用)(只有一个完整的页面)

(点击页面中导航链接不会刷新页面,只会做页面的局部更新)

二、基本使用

router-link最终转换为a标签

1. 安装vue-router

npm i vue-router

2. 应用插件

import VueRouter from 'vue-router'
Vue.use(VueRouter)

3.编写router配置项

创建文件 `src/router/index.js`
//该文件专门用于创建整个应用的路由器
//引入VueRouter
import VueRouter from "vue-router"

//引入路由组件
import About from '../pages/About'
import Home from '../pages/Home'

//创建router实例对象,管理一组一组的路由规则
const router = new VueRouter({
    routes:[
        {
            path:'/about',
            components:About
        },
        {
            path:'/home',
            component:Home
        }
    ]
})
//暴露router
export default router

4. 实现切换

<router-link active-class="active" :to="/about">About</router-link>

注:router-link最终转换为a标签,:to类似于hrefactive-class可配置高亮样式

5. 指定组件的呈现位置

<router-view></router-view>

注:

  • 路由组件专门放入新建pages文件夹中,一般组件通常存放在components文件夹中。

  • 通过切换,隐藏了的路由组件,默认是被销毁掉的,需要的时候再去挂载。

  • 每个组件都有自己的$route属性,里面存储着自己的路由信息

  • 整个应用只有一个router,可以通过组件的$router属性获取到

多级路由(嵌套路由)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1kbXWoRa-1647504541603)(C:\Users\gubing\AppData\Roaming\Typora\typora-user-images\image-20220315215545099.png)]

1.配置路由规则,使用children配置项

export default new VueRouter({
    routes:[
        {
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[			//配置子级路由
                {
                    path:'news',        //不用再加/
                    component:News,
                },
                {
                    path:'message',        //不用再加/
                    component:Message
                }
            ]
        }
    ]
})

2.跳转(写完整路径)

<router-link :to="/home/news">About</router-link>

三、路由的query参数

请添加图片描述

1.传递参数

Message.vue内)

<!-- 跳转路由并携带query参数 to的字符串写法 -->
<router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link>
<!-- 跳转路由并携带query参数 to的对象写法 -->
<router-link :to="{
                  	path:'/home/message/detail',
                  	query:{
                  		id:m.id,
                  		title:m.title
                  	}
                  }"
             > {{m.title}}</router-link>

2.接收参数

Detail.vue内)

{{$route.query.id}}
{{$route.query.title}}

四、命名路由

(简化路由的跳转)

1.命名

export default new VueRouter({
    routes:[
        {
            name:'xiaoxi',
            path:'/message',
            component:Message,
            children:[
                {
            		name:'xiangqing'
                    path:'detail',        //不用再加/
                    component:Detail,
                },
       		]
        },
})

2.简化跳转

<!-- 简化前写完整路径 -->
<router-link to="/message/detail">跳转</router-link>
<!-- 简化后通过名字跳转 -->
<router-link :to="{name:'xiangqing'}">跳转</router-link>
<!-- 简化写法配合传递参数 -->
<router-link :to="{
          			name:'xiangqing',
          			query:{
          					id:m.id,
          					title:m.title
          			}
        		}">
跳转</router-link>

五、路由的params参数

1.配置路由,声明接收params参数

{
     path:'/home',
     component:Home,
     children:[			//配置子级路由
         {
              path:'news',        //不用再加/
              component:News,
         },
         {
              path:'message',        //不用再加/
              component:Message,
              children:[
                  {
                      name:'xiangqing',
                      path:'detail/:id/:title',			//使用占位符声明接收params参数
                      component:Detail
                  }
              ]
         }
     ]
}

2.传递参数

Message.vue内)

<!-- 跳转路由并携带params参数 to的字符串写法 -->
<router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>

<!-- 跳转路由并携带query参数 to的对象写法 --> 
<!-- 必须写name 不能用path写 -->
<router-link :to="{
      name:'xiangqing',
      params:{
         id:m.id,
         title:m.title
      }
  }">
  {{m.title}}
</router-link>

注:携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置

3.接收参数

Detail.vue内)

$route.params.id
$route.params.title

六、路由的props配置

让路由组件更方便的收到参数

{
    name:'xiangqing',
    path:'detail',
    component:Detail,
        
    // props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给detail组件
    // props:{a:1,b:'hello'}    写死了
        
    // props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件
    // props:true
    // props的第三种写法,值为函数,该函数返回对象中的每一组key-value都会通过props传给Detail组件
    props($route){
        return {
            id:$route.query.id,
            title:$route.query.title
        }
    }
    //连续解构赋值
    /* props({query:{id,title}}){
        return {id,title}
    } */
}

Detail.vue内接收

props:['id','title']

七、 <router-link>replace模式

(控制路由跳转时操作浏览器历史记录的模式)

浏览器的历史记录有两种写入方式:分别为pushreplacepush是追加历史记录,replace是替换当前记录,默认为push

<router-link replace ...>News</router-link>

八、编程式路由导航

(不借助<router-link>实现路由跳转)
请添加图片描述

Message.vue内两个按钮的点击事件的具体内容

this.$router.push({
	name:'xiangqing',
	params:{
		id:xxx,
		title:xxx
	}
})
this.$router.replace({
	name:'xiangqing',
	params:{
		id:xxx,
		title:xxx
	}
})

请添加图片描述

this.$router.back()		//后退
this.$router.forward()	//前进
this.$router.go(-2) 	//正数连续前进n步,负数连续后退n步

九、缓存路由组件

让不展示的路由组件保持挂载,不被销毁

<!-- News指组件名 -->
<keep-alive include="News">
	<router-view></router-view>
</keep-alive>

<!-- 缓存多个路由组件 -->
<keep-alive :include="['News','Message']">
    <router-view></router-view>
</keep-alive>

十、两个新的生命周期钩子

路由组件独有的,用于捕获路由组件的激活状态

activated:路由组件被激活时触发

deactivated:路由组件失活时触发

十一、路由守卫

保护路由的安全(权限)

1.全局路由守卫

index.js

//全局前置路由守卫————初始化被调用,每次路由切换之前被调用
router.beforeEach((to,from,next)=>{
    console.log('前置路由守卫',to,from);
    if(to.meta.isAuth){     //判断是否需要鉴权
    // if(to.path === '/home/news' || to.path === '/home/message'){
        if(localStorage.getItem('school')==='xiaoxue'){
            next()
        }else{
            alert('学校名不对,无权限查看')
        }
    }else{
        next()			//放行
    }
})

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

注:meta:路由元信息,在路由组件内添加,设置isAuth值为true的组件需要鉴权

next():放行

2.独享路由守卫

某一个路由所独享的,在其路由配置内编写。(只有前置没有后置)

beforeEnter: (to, from, next) => {
    console.log('前置路由守卫',to,from);
    if(to.meta.isAuth){     //判断当前路由是否需要进行权限控制
    // if(to.path === '/home/news' || to.path === '/home/message'){
        if(localStorage.getItem('school')==='xiaoxue'){
                next()
        }else{
                alert('学校名不对,无权限查看')
        }
    }else{
        next()
    }
}

3.组件内路由守卫

在组件内编写。

//通过路由规则,进入该组件时被调用
beforeRouteEnter(to, from, next) {
  console.log("beforeRouteEnter", to, from);
  if (to.meta.isAuth) {
    //判断是否需要鉴权
    // if(to.path === '/home/news' || to.path === '/home/message'){
    if (localStorage.getItem("school") === "xiaoxue") {
      next();
    } else {
      alert("学校名不对,无权限查看");
    }
  } else {
    next();
  }
},
//通过路由规则,离开该组件时被调用
beforeRouteLeave(to, from, next) {
  console.log('About--beforeRouteLeave',to,from);
  next()
}

十二、路由器的两种工作模式

1.hash值:#及其后面的内容

请添加图片描述

#/about 都成为hash值

2.hash值不会成为路径的一部分,不会包含在HTTP请求中,不会带给服务器。

3.hash模式:兼容性好

4.history模式:兼容性差,应用部署上线后需要后端支持,解决刷新页面后404问题

const router = new VueRouter({
	mode:'hash',		//hash为默认值
	...
})
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值