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.mfbz.cn/a/574796.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

[Flutter3] 记录Dio的简单封装(一)

文章目录 效果使用ResponseEntity类DioManager封装_onResponse / _onDioException 的设计Response的处理catch处理 效果 请求成功/失败/异常的日志输出效果 成功: 失败:500 失败:404 网络异常: 使用 举个使用的例子, 在调用 DioManager的时候, 直接通过返回值的状态, 来…

ESP32开发WebSocket报错TRANSPORT_WS: Sec-WebSocket-Accept not found

我的芯片是ESP32-S3&#xff0c;用ESP-IDF框架进行开发的时候&#xff0c;用官方的WebSocket的example创建了项目。然后把WebSocket连接uri替换为自己的服务器后&#xff0c;运行到esp_websocket_client_start开始连接后&#xff0c;直接报错&#xff1a; E (10615) TRANSPORT…

网络爬虫之爬虫原理

** 爬虫概述 Python网络爬虫是利用Python编程语言编写的程序&#xff0c;通过互联网爬取特定网站的信息&#xff0c;并将其保存到本地计算机或数据库中。 """ 批量爬取各城市房价走势涨幅top10和跌幅top10 """ ​ from lxml import etree impor…

AJAX——黑马头条-数据管理平台项目

1.项目介绍 功能&#xff1a; 登录和权限判断查看文章内容列表&#xff08;筛选&#xff0c;分页&#xff09;编辑文章&#xff08;数据回显&#xff09;删除文章发布文章&#xff08;图片上传&#xff0c;富文本编辑器&#xff09; 2.项目准备 技术&#xff1a; 基于Bootst…

【韩国】UE5的MetaHuman确实可以导入Blender进行编辑。

UE5的MetaHuman确实可以导入Blender进行编辑。根据网络上的信息&#xff0c;你可以将MetaHuman模型导出为FBX文件&#xff0c;然后在Blender中进行修改。修改完成后&#xff0c;你可以将其重新导入到Unreal Engine 5中4。请注意&#xff0c;当你在Blender中编辑模型时&#xff…

第12章 最佳的UI体验——Material Design实战

第12章 最佳的UI体验——Material Design实战 其实长久以来&#xff0c;大多数人都认为Android系统的UI并不算美观&#xff0c;至少没有iOS系统的美观。以至于很多IT公司在进行应用界面设计的时候&#xff0c;为了保证双平台的统一性&#xff0c;强制要求Android端的界面风格必…

使用Shell终端访问Linux

一、实验目的 1、熟悉Linux文件系统访问命令&#xff1b; 2、熟悉常用 Linux Shell的命令&#xff1b; 3、熟悉在Linux文件系统中vi编辑器的使用&#xff1b; 4、进一步熟悉虚拟机网络连接模式与参数配置&#xff01; 二、实验内容 1、使用root帐号登陆到Linux的X-windows…

artifactory配置docker本地存储库

​一、概述 本地 Docker 存储库是我们部署和托管内部 Docker 镜像的位置。实际上&#xff0c;它是一个 Docker 注册表&#xff0c;能够托管的 Docker 镜像的集合。通过本地存储库&#xff0c;你可以保存、加载、共享和管理自己的 Docker 镜像&#xff0c;而无需依赖于外部的镜像…

API提取IP

API代理作为IP代理的一项重要业务&#xff0c;在绕开地域网络限制&#xff0c;提高作业效率等方面提供强大的技术支持。它能够帮助用户快速实现软件与软件间的交流&#xff0c;无障碍连通不同应用程序逻辑开发的系统应用。API代理用途范围广泛&#xff0c;如使用API提取代理IP、…

AcWing 1264. 动态求连续区间和 ,详细讲解线段树与树状数组(Python,篇一)

本篇博客主要介绍一下什么是线段树与树状数组&#xff0c;它们的原理与结构是怎样&#xff0c;并通过实际题型来讲解&#xff0c;篇一主要讲解线段树&#xff0c;下一篇博客讲解树状数组。 线段树与树状数组的区别和特点&#xff1a; 它们的时间复杂度都是O(nlogn) 存储方式…

使用navicate演示在 PostgreSQL 中使用 for 循环语句

1、简单循环示例 do $$ beginfor cnt in 1..10 loopraise notice cnt: %, cnt;end loop; end; $$ navicate中执行 2、循环查询 do $$ declare_record record; beginfor _record in (SELECT version,description FROM flyway_schema_history ORDER BY installed_rank desc li…

ios CI/CD 持续集成 组件化专题一 iOS 将图片打包成bundle

一、 创建 选择 macos 下的Bundle 二 、取名点击下一步 三、Base SDK 选择ios 四 、Build Active Architecture Only 五、Installation后面的内容删除 六、Skip Install 选择NO 七、Strip Debug Symbols During Copy 中"Release"项设置为 "YES" 八、COM…

书生·浦语 大模型(学习笔记-7)LMDeploy 量化部署 LLM-VLM 实践

目录 一、模型的部署 二、模型部署面临的问题 三、如何解决&#xff08;两种方法&#xff09; 四、LMDeploy相关知识 创建conda环境(漫长的等待) 五、使用LMDeploy与模型对话 六、设置最大KV Cache缓存大小 七、W4A16量化 八、客户端连接API服务器 一、模型的部署 二、…

leetcode-二叉树的镜像-91

题目要求 思路1 1.遍历一遍二叉树&#xff0c;将左边的结点对应创建一个右边的结点 2.用此方法空间复杂度O(n)&#xff0c;并不是最优 思路2 1.将一个结点的左右子树进行交换&#xff0c;如果左子树还有左右结点&#xff0c;就再交换左子树的左右结点&#xff0c;以此递归下去…

【树莓派】yolov5 Lite,目标检测,行人检测入侵报警

延续之前的程序&#xff1a; https://qq742971636.blog.csdn.net/article/details/138172400 文章目录 播放声音pygame不出声音怎么办&#xff08;调节音量&#xff09;树莓派上的音乐播放器&#xff08;可选&#xff09;命令行直接放歌&#xff08;尝试放mp3歌曲&#xff09; …

linux 上 jps 列出一堆 jar,如何快速定位 jar 文件启动位置?

例如&#xff0c;在 /data下有一个 xxx.jar &#xff0c;如果是通过 "java -jar /data/xxx.jar" 方式启动&#xff0c;则 jps会列出的名字中带 xxx.jar&#xff0c;这时再 "ps -ef | grep xxx.jar" 就会列出 更详细的信息&#xff0c;例如 "java -ja…

[iOS]CocoaPods安装和使用

1.了解brew、rvm、ruby、gem、cocaspods之间的关系 在 macOS 环境中&#xff0c;Brew、RVM、Ruby、Gem 和 CocoaPods 之间存在以下关系&#xff1a; Homebrew (Brew)&#xff1a;Homebrew 是 macOS 上的包管理器&#xff0c;用于安装和管理各种开源软件包。它使您能够轻松地从…

Windows 本地直接使用 SSH,SFTP 以及 SFTP下载文件到 Windows/mac 本地或上传(没有客户端时)

windows 本地打开 ssh 以及 sftp 等的方式 1.win(windows图标那个键) r 直接搜 然后从打开的位置运行 如果是打开 sftp 前面的 ssh 换一下成sftp 就行 直接从地址栏输入也可以直接转过去 通过 windows 的工具直接访问 sftp 后将文件下载到自己的windows 或 mac 上 先通过…

微软在汉诺威工业博览会上推出新制造业Copilot人工智能功能,强化Dynamics 365工具集

在近日于德国汉诺威举行的盛大工业博览会上&#xff0c;微软向全球展示了其最新推出的制造业人工智能功能&#xff0c;这些功能以Dynamics 365工具集为核心&#xff0c;旨在通过先进的AI技术为制造业带来前所未有的变革。 此次推出的新功能中&#xff0c;最为亮眼的是支持AI的…

Linux之ebpf(1)基础使用

Linux之ebpf(1)基础使用 Author: Once Day Date: 2024年4月20日 一位热衷于Linux学习和开发的菜鸟&#xff0c;试图谱写一场冒险之旅&#xff0c;也许终点只是一场白日梦… 漫漫长路&#xff0c;有人对你微笑过嘛… 全系列文章可以参考专栏&#xff1a;Linux基础知识_Once-D…
最新文章