Vue学习笔记|路由、详细、入门

这篇博客详细介绍了Vue的路由系统,包括路由的概念、前端路由与后端路由的区别、路由实例、嵌套路由、参数传递(params、query、props)、路由缓存、相关函数的使用、组件的销毁与保留、路由守卫以及路由器的两种工作模式。内容深入浅出,适合Vue初学者和进阶开发者学习。

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

目录

1.什么是路由

2.前端路由和后端路由的区别

3.路由应用实例

4.嵌套路由

5.路由传参

6. 路由缓存方式

7. router相关函数

8. 组件不被销毁

9.路由守卫

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

11. 注意点




1.什么是路由

路由是一组映射关系(key-value)
key是路径,value可能是function或者component

2.前端路由和后端路由的区别

2.1 后端路由
    1)value是function,用于处理客户端提交的请求
    2)工作过程:服务器接收到一个请求时,根据请求路径找到匹配的函数来处理请求,返回响应数据
    
2.2 前端路由
    1)value时component,用于展示页面内容
    2)工作过程:当浏览器的路径发生变化,对应的组件就会显示

3.路由应用实例

                                           

如图,左边是导航栏,右边是内容区。

当点击About,在内容区切换About组件的内容,

当点击Home,在内容区切换Home组件的内容,

3.1 下载router包

vue2:npm i router@3

vue3:npm i router@4

3.2 配置路由信息

假设有两个组件,对应两个路由

import VueRouter from 'vue-router'
import About from '../components/About'
import Home from '../components/Home'

export default new VueRouter({
    routes:[
        {
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home
        }
]
})

3.3 引入路由

在main.js文件引入路由

import VueRouter from 'vue-router'
import router from './router/index'

Vue.use(VueRouter)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  router:router
}).$mount('#app')

3.4 路由的使用

其中,<router-link>标签用于放导航栏,点击不同的导航,切换content中不同的组件

          <router-view>用于展示对应的组件内容

  <div id="app">
    <router-link to="/about" active-class="active">About</router-link>
    <router-link to="/home"  active-class="active">Home</router-link>
    <div class="content">
      <!--制定组件显示位置-->
      <router-view></router-view>
    </div>
  </div>

4.嵌套路由

                                        

 如图,当点击Home时,在Home组件中,又添加了News和Message路由,只需要在路由配置文件中,添加二级路由。

        {
            path:'/home',
            component:Home,
            children:[
                {
                    path:'message',
                    component:Message
                },
                {
                    path:'news',
                    component:News
                }
            ]
        }

5.路由传参

5.1 params传递参数

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

在path后使用“:变量名”作为占位符接收params参数

children:[
                        {
                            name:'detail',
                            path:'detail/:id/:title',
                            component:Detail,
                        }
                    ]

5.1.2 传递参数(二选一即可)

字符串传递参数

  <router-link :to="`/home/message/detail/${i.id}/${i.title}`">{{i.title}}</router-link>

对象传递参数

注意:对象传递参数只能使用name进行路由跳转,不能使用path

  <router-link :to="{
                    name:'detail',
                    params:{
                        id:i.id,
                        title:i.title
                    }

                }">{{i.title}}</router-link>

5.1.3 参数接收

       <p>{{$route.params.id}}}</p>
       <p>{{$route.params.title}}}</p>

5.2 query传递参数

5.2.1传递参数(二选一即可)

字符串传递参数

如图,可以向路由传递id和title,注意,变量需要在${}中写,整个字符串需要加上` `

 <li v-for="i in message" :key="i.id">
             
    <router-link :to="`/home/message/detail?id=${i.id}&title=${i.title}`">{{i.title}} 
    </router-link>
 
 </li>

对象传递参数

 <li v-for="i in message" :key="i.id">
             
    <router-link :to="{
                    path:'/home/message/detail',
                    query:{
                        id:i.id,
                        title:i.title
                    }}">{{i.title}}</router-link>
 
 </li>

5.2.2 参数的接收

参数保存在每个组件的$route.query中,可以通过以下获得组件传递的参数

 <div>
        <p>{{$route.query.id}}}</p>
        <p>{{$route.query.title}}}</p>
    </div>

5.3 props传递参数

5.2.1对象写法

传递key和value

      children:[
                        {
                            name:'detail',
                            path:'detail',
                            component:Detail,
                            props:{
                            id:'001',
                            title:'我是标题'
                            }
                        }
               ]

detail组件接收参数

 props:['id','title'],

detail组件使用参数

  <p>{{id}}</p>
  <p>{{title}}</p>

5.2.2 props为布尔值(结合params使用)

      children:[
                        {
                            name:'detail',
                            path:'detail',
                            component:Detail,
                            props:true
                        }
               ]

意义:将路由收到的所有params参数通过props传给Detail组件

接收参数和使用参数与5.2.1一致

5.2.3 函数写法(结合query使用)

     children:[
                        {
                            name:'detail',
                            path:'detail',
                            component:Detail,
                            props($route){
                                return{
                                    id:$route.query.id,
                                    title:$route.query.title
                                }
                            }
                        }
               ] 

接收参数和使用参数与5.2.1一致

6. 路由缓存方式

1. push方式

每改变路由,都会将最新的路由放入路由栈中,作为栈顶

2. replace方式

每改变路由,都会替换路由栈中已有的路由

7. router相关函数

使用除了<router-link>之外的标签进行路由的跳转

使用函数this.$router.push  和 函数this.$router.replace可以改变路由,两者的区别见第六条。

 <button @click="pushShow(i)">pushShow</button>
 <button @click="replaceShow(i)">replaceShow</button>


methods:{

            pushShow(i){
                this.$router.push({
                    name:'detail',
                    query:{
                        id:i.id,
                        title:i.title
                    }
                })
            },

            replaceShow(i){
                this.$router.replace({
                    name:'detail',
                    query:{
                        id:i.id,
                        title:i.title
                    }
                })
            },
}

使用路由进行前进后退

this.$router.back()  :  后退一步

this.$router.forward()  :  前进一步

this.$router.go(2)  :  前进两步

            back(){
                this.$router.back();
            },



            forward(){
                this.$router.forward();
            },



            go(){
                this.$router.go(2);
            }

8. 组件不被销毁

在router-view外边加入<keep-alive>,在include中写入不被销毁的组件名,这样即使当组件切换时,该组件也不会被销毁,从而可以保存一些数据

 <keep-alive include="News">
     <router-view></router-view>
 </keep-alive>

9.路由守卫

路由守卫的作用:前端判断是否操作者有权限使用该路由,若没有权限,则拦截路由

9.1全局前置路由守卫

初始化时候被调用,每次路由切换前被调用

当需要跳转的路径为/home/message 或者 /home/news时,判断是否有权限,并进行相关的操作

router.beforeEach((to, from, next )=>{
    if(to.path==='/home/message' || to.path==='/home/news'){
        if(判断是否有权限){
            //有权限
            next();
        }else{
            //没有权限相关操作
        }
    }else{
        next();
    }
})

9.2全局后置路由守卫

初始化时候被调用,每次路由切换后被调用

如下,在每次路由切换后,更改页面的标题

router.afterEach((to)=>{
    document.title=to.meta.title || '霍格沃兹';
})

其中,meta是配置在路由信息中的一个属性,meta是固定的一个key,不可修改

{
            name:'about',
            path:'/about',
            component:About,
            meta:{
                title:'关于'
            }
}

9.3 独享路由守卫(只有前置,没有后置)

独享前置路由守卫写在路由配置中,如下图所示。

{
                    name:'news',
                    path:'news',
                    component:News,
                    meta:{
                        title:'新闻',
                        isAuth:true
                    },
                    beforeEnter:(to,from,next)=>{
                        if(to.meta.isAuth){
                            if(localStorage.getItem('school')=='霍格沃兹'){
                                next();
                            }else {
                                alert('学校不对,无权查看');
                            }
                        }else{
                            next();
                        }
                    }

}

9.4 组件路由守卫

故名思意,组件路由守卫写在组件内,当进入组件前和离开组件的时候会调用组件路由守卫

        beforeRouteEnter(to,from,next){
        
           //进入组件前可以进行权限控制
        },
        beforeRouteLeave(to,from,next){
           
           //离开组件后可以进行数据的处理等等操作
            
        }

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

1)hash模式

在vue框架中,路由默认使用hash模式

特征:路径中带有#,hash值不会带给服务器

2)history模式

特质:history模式的路径不带#,且路径会带到服务器,并向服务器请求资源

使用history模式在服务器会出现问题:请求路径找不到,因为这是前端部分写的路径,服务器并不能识别。

解决:

安装插件

npm i connect-history-api-fallback
在服务器中使用插件,注意:要在引用静态资源之前使用插件

const express=require('express')
const history=require('connect-history-api-fallback')
const app=express();
app.use(history())
app.use(express.static(__dirname+'/static'))
app.get('/person',(req,resp)=>{
    resp.send({
        name:'小僵',
        age: 18
    })
})

11. 注意点

1)通过切换,被隐藏的组件,默认被销毁

2)整个组件只有一个router,可以通过组件的$router获取

3)每个组件都有$route属性,存路由信息,this.$route可以获取路由信息

4)二级路由path不需要加/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值