Vue 3 路由机制详解与实践

一、路由的理解

路由是指导用户界面导航的一种机制。它通过映射 URL 到应用程序的不同视图组件来实现页面间的切换和导航。

二、路由基本切换效果

路由基本切换效果指的是当用户在应用程序中进行页面导航时,通过路由可以实现页面的切换,从而展示不同的视图组件。

VUE文件

<template><h1 class="title">Vue路由测试</h1><div class="actives"><RouterLink to="/home" active-class="activeclass" class="active"  tag="button">首页</RouterLink><RouterLink to="/home" tag="button" class="button-link">码农</RouterLink><RouterLink :to="{ path: '/news' }" active-class="activeclass" class="active">新闻</RouterLink><RouterLink :to="{ name: '关于' }" active-class="activeclass" class="active">关于</RouterLink></div><div class="routerbox"><RouterView></RouterView></div>
</template><script lang="ts" setup name="Person">
import { RouterLink, RouterView } from 'vue-router'
import { ref, reactive, watch, onMounted } from 'vue';
</script>
</script>
<style lang='scss' scoped>
h1 {text-align: center;
}.actives {display: flex;justify-content: space-evenly;.button-link {display: inline-block;padding: 8px 16px;background-color: #007bff;color: #fff;border: none;border-radius: 4px;text-decoration: none;cursor: pointer;font-size: 16px;}.active {background-color: #808080;color: #fff;text-decoration: none;width: 100px;height: 50px;border-radius: 10%;text-align: center;line-height: 50px;font-size: 20px;}.active:hover {background-color: #354139;color: #ECC980;}.activeclass {background-color: #354139;color: #ECC980;text-decoration: none;width: 100px;height: 50px;border-radius: 10%;text-align: center;line-height: 50px;font-size: 20px;}
}.routerbox {margin: 0 auto;margin-top: 20px;width: 80%;height: 200px;border: 1px solid #000;border-radius: 10px;padding: 20px;
}
</style>

manin.ts文件

// 创建一个路由器,并暴露出去
//第一步:引入createRouter
import { createRouter, createWebHistory } from 'vue-router'//引入一个一个要呈现组件
import Home from '@/views/Home.vue'
import News from '@/views/News.vue'
import About from '@/views/About.vue'// 第二步:创建路由器
const router = createRouter({history: createWebHistory(),//路由器的工作模式routes: [//一个一个的路由规则{// 将默认路由重定向到 '/home'path: '/',name: '首页',redirect: '/home'},{path: '/home',name: '首页',component: Home},{path: '/news',name: '新闻',component: News},{path: '/about',name: '关于',component: About}]
})export default router

main.ts

//引入createApp用于创建应用
import { createApp } from 'vue'
//引入App根组件
import App from './App.vue'
// 引入路由器
import router from './route/route'//创建一个应用
const app = createApp(App)
// 使用路由器
app.use(router)
// 挂载整个应用到app容器中
app.mount('#app')

在这里插入图片描述

三、路由的两个注意点

1.路由组件通常存放在pagesviews文件夹,一般组件通常存放在components文件夹。
2.通过点击导航,视觉效果上“消失” 了的路由组件,默认是被卸载掉的,需要的时候再去挂载

四、路由器工作模式

1.history模式

优点:

  • URL 更加美观,不带有 #,更接近传统网站 URL
  • 利于 SEO 优化

缺点:

  • 后期项目上线,需要服务端配合处理路径问题,否则刷新会有 404 错误
const router = createRouter({history:createWebHistory(), //history模式})

网址显示:http://localhost:5173/home

  1. hash模式

优点:

  • 无需服务端配合,即可运行
  • 兼容性更好

缺点:

  • URL 带有 #,不太美观
  • 对 SEO 优化相对较差
const router = createRouter({history:createWebHashHistory(), //hash模式})

网址显示:http://localhost:5173/#/home

⭐不同点在于有无/#

五、路由 to 的两种写法

在 Vue 3 + TypeScript 中,可以使用对象字面量或者字符串形式来指定 to 属性。

对象字面量:to="{ name: 'Home' }"
字符串形式:to="/home"

六、路由命名路由

命名路由是指为特定路由指定一个名称,以便在代码中引用。这样做有助于在应用程序中进行路由导航时更清晰地指定目标路由。

// 创建路由器
const router = createRouter({history: createWebHistory(),//路由器的工作模式routes: [//一个一个的路由规则{// 将默认路由重定向到 '/home'path: '/',redirect: '/home'},{path: '/home',name: '首页',component: Home},{path: '/news',name: '新闻',component: News},{path: '/about',name: '关于',component: About}]
})
export default router

七、路由嵌套路由

路由嵌套是指在一个路由下定义子路由,通过这种方式可以构建复杂的页面结构和导航层次。

  1. 编写News的子路由:Detail.vue
  2. 配置路由规则,使用children配置项:
const router = createRouter({history: createWebHistory(),//路由器的工作模式routes: [//一个一个的路由规则{path: '/news',name: '新闻',component: '@/views/News.vue',children: [{path: '/detal',component: '@/views/detal.vue'}]}]
})
export default router
  1. 跳转
<li v-for="item in newsList" :key="item.id"><RouterLink to="/news/detal" :active-data="item">{{ item.title }}</RouterLink>
</li>
  1. 记得去news组件中预留一个<router-view>
<template><div class="flex"><div class="news"><ul><li v-for="item in newsList" :key="item.id"><RouterLink to="/news/detal">{{ item.title }}</RouterLink></li></ul></div><div class="router-content"><RouterView></RouterView></div></div>
</template>
<script setup lang="ts" name="News">
import { ref, reactive, watch, onMounted } from 'vue';
import { RouterLink, RouterView } from 'vue-router';
const newsList = ref([{ id: 1, title: '标题1', content: '内容1' },{ id: 2, title: '标题2', content: '内容2' },{ id: 3, title: '标题3', content: '内容3' },{ id: 4, title: '标题4', content: '内容4' },{ id: 5, title: '标题5', content: '内容5' },
])
</script>
<style lang='scss' scoped>
.flex {display: flex;justify-content: flex-start;.news {ul {margin: 0;padding: 0 10px 0 0;li {list-style-type: none;a {text-decoration: none;}}}}.router-content {width: 80%;border-radius: 10px;padding: 5px;border: #000 solid 1px;}
}
</style>

八、路由传参

  1. 路由 query 参数
    Query 参数是指在 URL 中以 ? 开头的参数,用于传递额外的信息给路由目标组件。在 Vue 3 + TypeScript 中,可以通过 $route.query 来获取这些参数。

1.query参数

(1)传递参数

<!-- 方式一:跳转并携带query参数(to的字符串写法) -->
<RouterLink :to="`/news/detail?id=${item.id}&title=${item.title}&content=${item.content}`">{{ item.title }}
</RouterLink><!-- 方式二:跳转并携带query参数(to的对象写法) -->
<RouterLink :to="{path: '/news/detail',query: {id: item.id,title: item.title,content: item.content}
}">{{ item.title }}</RouterLink>

(2)接收参数:

import { ref, watchEffect, toRefs } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
let { query } = toRefs(route)

(3)路由配置


const router = createRouter({history: createWebHistory(),//路由器的工作模式routes: [{path: '/news',name: '新闻',component: News,children: [{name:'detail',path: '/news/detail',component: Detal}]}
])export default router

2.params参数

Params 参数是指在 URL 中使用动态路由参数的一种方式,通过这种方式可以在路由之间传递数据。在 Vue 3 + TypeScript 中,可以通过 $route.params 来获取这些参数。

(1)传递参数

<!-- 第一种方法 -->
<RouterLink :to="`/news/detail/${item.id}/${item.title}/${item.content}`">{{ item.title }}</RouterLink><!-- 第二种方法 -->
<RouterLink :to="{name: 'detail',params: {id: item.id,title: item.title,content: item.content,}
}">{{ item.title }}</RouterLink>

(2)接收参数

import { toRefs } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
let { params } = toRefs(route)
console.log(params.value);

(3)路由配置

const router = createRouter({history: createWebHistory(),//路由器的工作模式routes: [{path: '/news',name: '新闻',component: News,children: [{name:'detail',path: '/news/detail/:id/:title/:content?',//id和title参数是必须的,但content参数可以省略component: Detal}]}
])export default router

注意:

备注1:传递params参数时,若使用to的对象写法,必须使用name配置项,不能用path
备注2:传递params参数时,需要提前在规则中占位。

九、路由 props 配置

让路由组件更方便的收到参数(可以将路由参数作为props传给组件)

(1)传递参数

const router = createRouter({history: createWebHistory(),//路由器的工作模式routes: [//一个一个的路由规则{path: '/news',name: '新闻',component: News,children: [{name:'xiang',path:'detail/:id/:title/:content',component:Detail,// ⭐⭐第一种写法:将路由收到的所有params参数作为props传给路由组件props: true,// ⭐⭐第二种写法:函数写法,可以自己决定将什么作为props给路由组件props(route) {return route.query}// 第三种写法(几乎用不到):对象写法,可以自己决定将什么作为props给路由组件props :{id:1,title:'标题',content:'内容'}]}]
})
export default router

等同于 <Detail :id="1" :title="标题" :content="内容" /> 这样的 prop传值

(2)接收参数

<template><div>编号:{{ id }}标题:{{ title }}内容:{{ content }}</div>
</template><script lang="ts" setup name="Person">defineProps(['id','title','content',])
</script>

十、路由 replace 属性

replace 属性是指在导航时替换当前路由历史记录而不是添加新记录。在某些情况下,使用 replace 可以更好地管理路由历史。

  1. 作用:控制路由跳转时操作浏览器历史记录的模式。
  2. 浏览器的历史记录有两种写入方式:分别为pushreplace
  • push是追加历史记录(默认值)。
  • replace是替换当前记录。
  1. 开启replace模式路由跳转时加了replace的路由,导航就不会留下历史记录
<RouterLink replace .......>News</RouterLink>

十一、路由编程式路由导航

编程式路由导航是指通过 JavaScript 代码来进行页面导航,可以在组件方法中使用 $router 对象来实现。

<template><div><button @click="navGetTo()">点我跳转新闻页</button></div>
</template>
<script lang="ts" setup name="Person">
import { useRouter } from 'vue-router';
const router = useRouter()function navGetTo() {router.push('/news')
}
</script>

应用场景:

符合条件跳转,登陆成功跳转个人主页、整点秒杀跳转鼠标滑过跳转等等

十二、路由重定向

路由重定向是指当用户访问某个特定路径时自动将其重定向到另一个路径,通常用于处理用户访问的旧路径或者错误路径。

 {// 将默认路由重定向到 '/home'path: '/',redirect: '/home'}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/640005.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

cookie与session区别和联系

在Web应用中&#xff0c;HTTP协议是无状态的&#xff0c;每次请求都是独立的&#xff0c;服务器无法直接识别一个用户的不同请求之间的关联。这就导致了如果我们希望在一个会话中保持一些数据的状态&#xff0c;比如用户的身份认证信息、购物车内容等&#xff0c;就需要借助Coo…

【昇腾产品应用】英码科技EA500I基于昇腾Mind SDK实现实时人体关键点检测

在教育、体育、安防、交通、医疗等领域中&#xff0c;实时人体关键点检测应用发挥着至关重要的作用&#xff0c;比如在体育训练时&#xff0c;实时人体关键点检测可以精确、实时地捕捉运动员的动作&#xff0c;从而进行动作分析和优化&#xff1b;在安防应用场景中&#xff0c;…

vector的底层与使用

前言&#xff1a;vector是顺序表&#xff08;本质也是数组&#xff09; 文档参考网站&#xff1a;https://legacy.cplusplus.com/reference/vector/vector/vector/ //底层代码 #include<assert.h> #include<iostream> #include<vector> #include<string&g…

Kafak详解(1)

简介 消息队列 为什么要有消息队列 图-1 消息队列的使用 消息队列 1)消息Message&#xff1a;网络中的两台计算机或者两个通讯设备之间传递的数据。例如说&#xff1a;文本、音乐、视频等内容。 2)队列Queue&#xff1a;一种特殊的线性表(数据元素首尾相接)&#xff0c;特…

echarts折线图默认不显示数据圆点,鼠标划上之后折线图才显示圆点

只需要设置showSymbol为false就可以了&#xff0c;表示只在 tooltip hover 的时候显示。 代码如下&#xff1a; option {tooltip: {trigger: axis},xAxis: {type: category,data: [Mon, Tue, Wed, Thu, Fri, Sat, Sun]},yAxis: {type: value},series: [{data: [150, 230, 224…

什么是防抖和节流?有什么区别? 如何实现?

防抖&#xff08;Debounce&#xff09;和节流&#xff08;Throttle&#xff09;是两种常用的技术手段&#xff0c;主要用于控制某个函数在一定时间内触发的次数&#xff0c;以减少触发频率&#xff0c;提高性能并避免资源浪费。 防抖&#xff08;Debounce&#xff09;的工作原…

图像哈希:GLCM+DCT

文章信息 作者&#xff1a;Ziqing Huang期刊&#xff1a;IEEE&#xff08;一区&#xff09;题目&#xff1a;Perceptual Image Hashing with Texture and Invariant Vector Distance for Copy Detection 目的、实验步骤及结论 目的&#xff1a;使用GLCM进行全局特征的提取&am…

Python 数据库简化操作:dataset 库介绍

文章目录 Python 数据库简化操作&#xff1a;dataset 库介绍第一部分&#xff1a;背景介绍第二部分&#xff1a;库是什么&#xff1f;第三部分&#xff1a;如何安装这个库&#xff1f;第四部分&#xff1a;库函数使用方法第五部分&#xff1a;场景应用第六部分&#xff1a;常见…

C++初阶学习第二弹——C++入门(下)

C入门&#xff08;上&#xff09;&#xff1a;C初阶学习第一弹——C入门&#xff08;上&#xff09;-CSDN博客 目录 一、引用 1.1 引用的实质 1.2 引用的用法 二、函数重载 三、内敛函数 四、auto关键字 五、总结 前言&#xff1a; 在上面一章我们已经讲解了C的一些基本…

echarts 双堆叠柱状图(数据整理)

1.后台返回的数据格式 {"code": "0000","message": "","messageCode": "操作成功","sign": null,"detail": null,"data": {"pieChart": [{"key": "产品…

Git下载安装

天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物。 每个人都有惰性&#xff0c;但不断学习是好好生活的根本&#xff0c;共勉&#xff01; 文章均为学习整理笔记&#xff0c;分享记录为主&#xff0c;如有错误请指正&#xff0c;共同学习进步。…

就业班 第三阶段(负载均衡) 2401--4.19 day3 nginx3

二、企业 keepalived 高可用项目实战 1、Keepalived VRRP 介绍 keepalived是什么keepalived是集群管理中保证集群高可用的一个服务软件&#xff0c;用来防止单点故障。 ​ keepalived工作原理keepalived是以VRRP协议为实现基础的&#xff0c;VRRP全称Virtual Router Redundan…