Vue-VueRouter路由的使用(超详细)

1.定义

理解:一个路由(route)就是一组映射关系(key-value),多个路由依靠路由器(router)进行管理

前端路由:key是路径,value是组件

2.基本使用

1.安装vue-router

npm i vue-router

2.应用插件

Vue.use(Router)

3.编写router配置项

在router.js中(如果没有这个文件就自己创建)

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
    routes:[
        {path:'/xxx',component:xxx,},//page是页面的路径,component是页面
        {path:'/yyy',component:yyy,  
    	]
})

​ 4.路由的切换

<router-link to="/home/new">New</router-link>

​ 5.指定展示位置

<router-view></router-view>

3.嵌套路由的使用

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

routes:[
        {path:'/about',component:About,},
        {path:'/home',component:Home,
            redirect:'/home/message',
         //在children配置项中添加需要嵌套的路由
            children:[
                {path:'new',component:New},
                {path:'message',component:Message}
            ]}
    ]

2.路由跳转(要写完整路径)

<router-link to="/home/message">message</router-link>

示例:

在这里插入图片描述

4.路由的query参数

1.传递参数

1.方式一

to的字符串写法,将需要传递的参数作为字符串传递

2.方式二

to的对象写法,将在对象中配置query项,并将参数存入

//方式一:to的字符串写法
<router-link  :to="`/home/message/detail?id=001&title=666`" >{{item.id}}</router-link>
//方式二:to的对象写法
<router-link :to="{
                  path:'/home/message/detail',
                  query:{
                  id:001
                  title:666
                  }}">
</router-link>
2.接收参数
$route.query.id
$route.query.title

5.路由的命名

1.作用:可以简化路由跳转的信息

2.如何使用

​ 1.给路由命名

 routes:[
        {path:'/about',component:About,},
        {path:'/home',component:Home,
         	name:'home',//通过name配置项对路由命名
            redirect:'/home/message',//可以在进入home组件时,直接在home的内容框中渲染message组件的信息
            children:[
                {path:'new',component:New},
                {path:'message',component:Message,
                    children:[
                        {name:'detail',
                        path:'detail/:id/:title',
                        component:Detail,}
                    ]}
            ]}
    ]

​ 2.作用(简化路径信息)

//简化前,需要写完整的路径
<router-link to="/home/message/detail">message</router-link>
//简化后,直接通过name跳转,但需要写在对象中
<router-link :to="{name:'detail'}">
</router-link>

6.路由的params参数

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

 routes:[
        {path:'/about',component:About,},
        {path:'/home',component:Home,
            redirect:'/home/message',
            children:[
                {path:'new',component:New},
                {path:'message',component:Message,
                    children:[
                        {name:'detail',
                        path:'detail/:id/:title',//使用占位符声明接收params参数
                        component:Detail,}
                    ]}
            ]}
    ]

​ 2.传递参数

//方式一 to的字符串写法
<router-link  :to="`/home/message/detail/001/666`" >{{item.id}}</router-link>
//方式二 to的对象写法
<router-link :to="{
                name:'detail',
                params:{
                    id:001,
                    title:666
                }}">
跳转</router-link>

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

3.接收参数

$route.query.id
$route.query.title

7.路由的props配置

作用:让路由组件接收参数更加简便

写法一:props为对象,将该对象传递给子组件

写法二:props值为布尔值,若为true,则把路由收到的所有params参数通过props传给子路由组件

写法三:props值为函数,该函数返回的对象中的每一组key-value都会通过props传给子路由组件


假设我们需要从数据从一个路由传递给他的子路由

父级路由:将id和title作为参数传递给子路由

<div>
        <ul>
           <li v-for="item in messageList" :key="item.id">
               //to的字符串方式
            <router-link  :to="`/home/message/detail/${item.id}/${item.title}`" >{{item.id}}</router-link>
               //to的对象方式
            <!-- <router-link :to="{
                name:'detail',
                params:{
                    id:item.id,
                    title:item.title
                }}">
            </router-link> -->
           </li> 
        </ul>
        <div>
            <router-view></router-view>
        </div>
    </div>
export default {
    data() {
        return {
            messageList:[
                {id:'001',title:'111'},
                {id:'002',title:'222'},
                {id:'003',title:'333'},
            ]
        }
    },
}

router.js

export default new Router({
    routes:[
        {path:'/about',component:About,},
        {path:'/home',component:Home,
            redirect:'/home/message',
            children:[
                {path:'new',component:New},
                {path:'message',component:Message,
                    children:[
                        {name:'detail',
                        path:'detail/:id/:title',
                         //第一种写法:props为对象,将该对象传递给子组件
                         props:{id:xxx,title:xxx}
                        //第二种写法:props值为布尔值,若为true,则把路由收到的所有params参数通过props传给子路由组件
                        props:true,//将props配置项设为true
                         //第三种写法:props值为函数,该函数返回的对象中的每一组key-value都会通过props传给子路由组件
                        props(route){
                        	return{
                        		//如果父级路由传来的参数形式是params,则接收也用params,如果为query,就用route.query.xxx
								id:route.params.id,
                        		title:route.query.title
                        	}
                        }
                        component:Detail,}
                    ]}
            ]}
    ]
})

子路由:

 <div>
      <h1> title:{{id}} </h1>   
      <h1> name:{{title}}</h1>
  </div>

8.< router-link >的replace属性

1.作用:控制路由跳转时操作浏览器历史记录的模式

2.浏览器的历史记录有两种写入方式,分别为pushreplacepush是追加历史记录,replace是替换当前记录,跳转路由时默认为push,因为浏览器操作是栈模式,每一次操纵都会压栈,push是将新的记录压入栈中而replace是先将栈顶元素删除并压栈

3.如何开启replace模式

<router-link replace>xxx</router-linkrouter-link>

9.编程式路由导航

1.作用:不借助< router-link >实现路由跳转,让路由跳转更加灵活

2.实现

pushreplace两种路由模式以及forwardbackgo三种方法

    <div>
        <ul>
           <li v-for="item in messageList" :key="item.id">
            //replace模式
           <button @click="$router.replace({
                name:'detail',
                params:{
                    id:item.id,
                    title:item.title
                }
            })">跳转至detail页面</button>
               //push模式
              <button @click="$router.push({
                name:'detail',
                params:{
                    id:item.id,
                    title:item.title
                }
            })">跳转至detail页面</button>
               <button @click="$router.forward()">前进</button>
               <button @click="$router.back()">后退</button>
               <button @click="$router.go(3)">可前可后,里面的数字代表前进/后退的步数</button>
           </li> 
        </ul>
        <div>
            <router-view></router-view>
        </div>
    </div>

10.缓存路由组件

1.作用:让不展示的路由组件保持挂载,不被销毁

2.具体编码

使用< keep-alive>标签将路由展示区包裹,include的作用是指定保持挂载的组件,不需要保持挂载的组件不需要添加进include中,

注意:include内的参数是组件名

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

//缓存一个路由组件
<keep-alive include="New">
    <router-view></router-view>
</keep-alive>

效果

在这里插入图片描述

11.两个新的生命周期钩子

1.作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态

2.具体名字:

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

12.路由守卫

1.作用:对理由进行权限控制

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

3.全局守卫

export default new Router({
    routes:[
        {path:'/about',component:About,},
        {path:'/home',component:Home,
            redirect:'/home/message',
            children:[
                {path:'new',component:New,meta:{isAuth:true}},
                {path:'message',component:Message}
            ]}
    ]
})
//全局前置守卫:初始化时执行、每次路由切换前执行
router.beforeEach((to,from,next)=>{
  if(to.meta.isAuth){//判断当前路由是否需要进行权限控制,meta时在路由中的一个属性,里面的内容自定义
    const tokenStr = window.sessionStorage.getItem('token')
    if(!tokenStr){
      return next('/home')
    }
  }
  next()//放行
})
//全局后置守卫,初始化时执行、每次路由切换后执行,后置首位没有next的概念,因为放行操作已经在前置守卫中执行了
router.afterEach((to,from)=>{
  if(to.meta.title){
    document.title = to.meta.title
  }
})

4.独享路由守卫:

独享路由守卫需要写在具体的路由中

routes:[
        {path:'/about',component:About,},
        {path:'/home',component:Home,
            redirect:'/home/message',
            children:[
                {
                    path:'new',
                    component:New,
                    meta:{isAuth:true},
                    //独享路由守卫,用法与前置守卫一样
                    beforeEnter:(to,from,next)=>{
                        if(to.meta.isAuth){
                            const tokenStr = window.sessionStorage.getItem('token')
                            if(!tokenStr){
                              return next('/home')
                            }
                          }
                          next()//放行
                    }   
                },
            ]}
    ]

5.组件内守卫:

进入守卫:当从另一个组件进入该组件时,执行beforeRouteEnter方法

离开守卫:当从该组件时进入另一个组件时,执行beforeRouteLeave方法

必须定义在具体的组件中,在VC中调用

export default{
    ...
	//通过路由规则进入该组件时被调用,用法与上述路由守卫类似
    beforeRouteEnter(to,from,next){

    }
    //通过路由规则离开该组件时被调用
    beforeRouteLeave(to,from,next){

    }
}

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

1.对于一个url来说 hash值的定义:#及其后面的内容就是hash值

2.hash值不会包含在http请求中,即hash值不会带给服务器

3.hash模式:

​ 1.地址中永远携带#号

​ 2.地址容易被app标记为不合法

​ 3.兼容性较好

4.history模式:

​ 1.兼容性较hash模式较差

​ 2.刷新页面服务器端容易出现404的问题

5.解决history刷新出现404的问题:

在node项目中

下载第三方库

npm install --save connect-history-api-fallback

引入

var history = require('connect-history-api-fallback');

使用:

var app = express();
app.use(history());
  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 中,你可以使用 Vue Router 进行路由跳转。下面是一些基本的步骤: 1. 首先,确保你已经安装了 Vue Router。你可以通过运行以下命令来安装它: ``` npm install vue-router@next ``` 2. 在你的主文件(例如 `main.js` 或 `main.ts`)中导入 Vue Router 和你的路由配置: ```javascript import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; import App from './App.vue'; import Home from './views/Home.vue'; import About from './views/About.vue'; const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ]; const router = createRouter({ history: createWebHistory(), routes }); const app = createApp(App); app.use(router); app.mount('#app'); ``` 在上面的示例中,我们创建了两个路由:`/` 对应 `Home` 组件,`/about` 对应 `About` 组件。你可以根据自己的需求添加更多的路由。 3. 在你的组件中使用路由跳转,你可以使用 `<router-link>` 组件或 `$router.push` 方法。 使用 `<router-link>` 组件: ```html <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> ``` 使用 `$router.push` 方法: ```javascript // 在方法中调用 methods: { goToHome() { this.$router.push('/'); }, goToAbout() { this.$router.push('/about'); } } // 或者在模板中调用 <button @click="$router.push('/')">Go to Home</button> <button @click="$router.push('/about')">Go to About</button> ``` 这样,当用户点击链接或按钮时,路由就会进行跳转。 这只是一个基本的示例,你还可以使用更多的 Vue Router 功能,如路由参数、嵌套路由路由守卫等。你可以参考 Vue Router 的官方文档来了解更多信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值