Vue3-路由详解

在这里插入图片描述


更多相关内容可查看

路由

附git地址:https://gitee.com/its-a-little-bad/vue.git
git中有以下相关代码,可以拉取测试,node版本为20.8.1,详解看注释

对路由的理解

  • 动态路由匹配:你可以基于 URL 的不同部分来动态地匹配和渲染不同的组件。
  • 嵌套路由:你可以将路由映射到嵌套的组件结构中,以构建复杂的用户界面。
  • 路由参数:你可以在 URL 中添加参数,并在组件中访问它们。
  • 查询参数和哈希片段:除了路径参数外,你还可以从 URL 的查询字符串或哈希片段中访问数据。
  • 滚动行为:你可以自定义路由切换时的滚动行为。
  • 导航守卫:你可以在路由切换前、切换后或切换失败时运行一些逻辑,如检查用户是否已登录或加载异步数据。
  • 路由懒加载:Vue Router 支持将路由组件异步加载,以提高应用的初始加载速度。
  • 编程式导航:除了使用 组件进行声明式导航外,你还可以使用 Vue Router 的 API 进行编程式导航。
  • HTML5 History 模式:默认情况下,Vue Router 使用 HTML5 History 模式来构建
    URL,但它也支持传统的哈希模式(使用 URL 的哈希片段)。
  • 过渡效果:你可以使用 Vue 的过渡组件()为路由切换添加过渡效果。

安装 Vue Router

npm install vue-router
# 或者  
yarn add vue-router

基本切换效果

  • Vue3中要使用vue-router的最新版本,目前是4版本。
  • 路由配置文件代码如下:
import {createRouter,createWebHistory} from 'vue-router'
import Home from '@/pages/Home.vue'
import News from '@/pages/News.vue'
import About from '@/pages/About.vue'

const router = createRouter({
	history:createWebHistory(),//工作模式 ,还有一种是hash
	routes:[
		{
			path:'/home', //pages下的vue文件的路径
			component:Home //pages下的vue文件
		},
		{
			path:'/about',
			component:About
		}
	]
})
export default router //向外抛出
  • main.tsmain.js代码如下:
import router from './router/index'
app.use(router)//使用路由
app.mount('#app')//挂载
  • App.vue代码如下
<template>
  <div class="app">
    <h2 class="title">Vue路由测试</h2>
    <!-- 导航区 -->
    <div class="navigate">
      <RouterLink to="/home" active-class="active">首页</RouterLink>
      <RouterLink to="/news" active-class="active">新闻</RouterLink>
      <RouterLink to="/about" active-class="active">关于</RouterLink>
    </div>
    <!-- 展示区 -->
    <div class="main-content">
      <RouterView></RouterView>
    </div>
  </div>
</template>

<script lang="ts" setup name="App">
  import {RouterLink,RouterView} from 'vue-router'  
</script>

两个注意点

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

路由器工作模式

  1. history模式

优点:URL更加美观,不带有#,更接近传统的网站URL

缺点:后期项目上线,需要服务端配合处理路径问题,否则刷新会有404错误。

const router = createRouter({
  	history:createWebHistory(), //history模式
  	/******/
})
  1. hash模式

优点:兼容性更好,因为不需要服务器端处理路径。

缺点:URL带有#不太美观,且在SEO优化方面相对较差。

const router = createRouter({
  	history:createWebHashHistory(), //hash模式
  	/******/
})

to的两种写法

<!-- 第一种:to的字符串写法 -->
<router-link active-class="active" to="/home">主页</router-link>

<!-- 第二种:to的对象写法 -->
<router-link active-class="active" :to="{path:'/home'}">Home</router-link>

命名路由

作用:可以简化路由跳转及传参。

给路由规则命名:

routes:[
  {
    name:'zhuye',
    path:'/home',
    component:Home
  },
  {
    name:'xinwen',
    path:'/news',
    component:News,
  },
  {
    name:'guanyu',
    path:'/about',
    component:About
  }
]

跳转路由:

<!--简化前:需要写完整的路径(to的字符串写法) -->
<router-link to="/news/detail">跳转</router-link>

<!--简化后:直接通过名字跳转(to的对象写法配合name属性) -->
<router-link :to="{name:'guanyu'}">跳转</router-link>

嵌套路由

  1. 编写News的子路由:Detail.vue
  2. 配置路由规则,使用children配置项:
const router = createRouter({
  history:createWebHistory(),
	routes:[
		{
			name:'zhuye',
			path:'/home',
			component:Home
		},
		{
			name:'xinwen',
			path:'/news',
			component:News,
			children:[
				{
					name:'xiang',
					path:'detail',
					component:Detail
				}
			]
		},
		{
			name:'guanyu',
			path:'/about',
			component:About
		}
	]
})
export default router
  1. 跳转路由(记得要加完整路径):
<router-link to="/news/detail">xxxx</router-link>
<!---->
<router-link :to="{path:'/news/detail'}">xxxx</router-link>
  1. 记得去Home组件中预留一个<router-view>
<template>
  <div class="news">
    <nav class="news-list">
      <RouterLink v-for="news in newsList" :key="news.id" :to="{path:'/news/detail'}">
        {{news.name}}
      </RouterLink>
    </nav>
    <div class="news-detail">
      <RouterView/>
    </div>
  </div>
</template>

路由传参

query参数

  1. 传递参数
<!-- 跳转并携带query参数(to的字符串写法) -->
<router-link to="/news/detail?a=1&b=2&content=欢迎你">
	跳转
</router-link>
				
<!-- 跳转并携带query参数(to的对象写法) -->
<RouterLink 
  :to="{
    //name:'xiang', //用name也可以跳转
    path:'/news/detail',
    query:{
      id:news.id,
      title:news.title,
      content:news.content
    }
  }"
>
  {{news.title}}
</RouterLink>
  1. 接收参数:
import {useRoute} from 'vue-router'
const route = useRoute()
// 打印query参数
console.log(route.query)

params参数

  1. 传递参数
<!-- 跳转并携带params参数(to的字符串写法) -->
<RouterLink :to="`/news/detail/001/新闻001/内容001`">{{news.title}}</RouterLink>
				
<!-- 跳转并携带params参数(to的对象写法) -->
<RouterLink 
  :to="{
    name:'xiang', //用name跳转
    params:{
      id:news.id,
      title:news.title,
      content:news.title
    }
  }"
>
  {{news.title}}
</RouterLink>
  1. 接收参数:
import {useRoute} from 'vue-router'
const route = useRoute()
// 打印params参数
console.log(route.params)

备注1:传递params参数时,若使用to的对象写法,必须使用name配置项,不能用path

备注2:传递params参数时,需要提前在规则中占位。

路由的props配置

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

{
	name:'xiang',
	path:'detail/:id/:title/:content',
	component:Detail,

  // props的对象写法,作用:把对象中的每一组key-value作为props传给Detail组件
  // props:{a:1,b:2,c:3}, 

  // props的布尔值写法,作用:把收到了每一组params参数,作为props传给Detail组件
  // props:true
  
  // props的函数写法,作用:把返回的对象中每一组key-value作为props传给Detail组件
  props(route){
    return route.query
  }
}

replace属性

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

编程式导航

路由组件的两个重要的属性:$route$router变成了两个hooks

import {useRoute,useRouter} from 'vue-router'

const route = useRoute()
const router = useRouter()

console.log(route.query)
console.log(route.parmas)
console.log(router.push)
console.log(router.replace)

重定向

  1. 作用:将特定的路径,重新定向到已有路由。
  2. 具体编码:
{
    path:'/',
    redirect:'/about'
}
  • 35
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue Router 是 Vue.js 官方的路由管理器,它和 Vue.js 的核心深度集成,让构建单页应用变得易如反掌。Vue Router 通过管理应用的URL,实现了组件的切换,让用户可以在单页应用中享受到和传统多页应用相同的体验。 在 Vue Router 中,我们可以通过 <router-view> 组件来渲染匹配到的组件。它是 Vue Router 中最重要的组件之一。当我们的路由切换时,<router-view> 组件可以根据当前的 URL 自动切换到匹配到的组件,不需要手动处理。 下面是一些关于 <router-view> 组件使用的详解: 1. <router-view> 组件是函数式组件,它不会渲染出任何实际的 HTML 元素,而是渲染出匹配到的组件。 2. 每次路由切换时,<router-view> 组件会销毁旧的组件并创建新的组件实例。 3. 如果在路由配置中没有指定组件的 name 属性,则默认使用默认组件。 4. 如果有多个 <router-view> 组件,需要在路由配置中指定每个 <router-view> 组件应该渲染哪个组件。 5. 如果没有匹配到任何路由,则 <router-view> 组件不会渲染出任何内容。 6. 可以使用 <keep-alive> 包裹 <router-view> 组件,让路由切换时保持组件状态不被销毁。 7. 可以使用 <transition> 包裹 <router-view> 组件,为路由切换添加过渡动画效果。 总的来说,<router-view> 组件是 Vue Router 中最常用的组件之一。它可以让我们在构建单页应用时轻松地管理路由和组件,为用户提供更好的体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来一杯龙舌兰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值