vue-router基础

简介: vue-router基础

vue-router基础

index文件配置

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    name: "Index",
    path: "/",
    component: () => import(`../components/Index/Index.vue`),
  },
  {
    name: "AddArtical",
    path: "/addartical",
    component: () => import(`../components/AddContent/AddArtical.vue`),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

使用router

在使用router时记得使用<RouterView>标签,来作为一个“容器”,进行组件的渲染。不然router配置的路由不会生效。

编程式导航

我们可以定义name的属性,来使用name的值来跳转页面

const routes: Array<RouteRecordRaw> = [
  {
    name: "Index",
    path: "/",
    component: () => import(`../components/Index/Index.vue`),
  },
  {
    name: "AddArtical",
    path: "/addartical",
    component: () => import(`../components/AddContent/AddArtical.vue`),
  },
];

然后通过传对象的方式来进行跳转

<RouterLink :to="{ name: 'Index' }">首页</RouterLink>

或者使用事件函数,通过编程式导航来跳转

<button @click="changePage('AddArtical')">添加文章</button>
import { useRouter } from "vue-router";
const router = useRouter();
const changePage = (url: string) => {
  // 如果传url地址
  // router.push(url)
    
  // 如果传name
  router.push({
    name: url,
  });
};

历史记录

我们可以在router-link中使用replace属性来使这个跳转没有历史记录

<RouterLink replace to="/addartical">添加文章</RouterLink>

如果是编程式导航,我们可以把router.push()改为router.replace()

对于历史记录的前进倒退,我们可以使用router.go()和router.back(),参数为数字,如1,-1。

传入的几,就前进或者倒退几个历史记录,router.go(0)为刷新页面

路由传参

query传参的跳转用name和path都可以

<button @click="toQuery(item)" class="btn btn-outline btn-primary">
  路由传参
</button>
import { useRouter } from "vue-router";
const router = useRouter();
const item = {
  name: "kevin",
  age: 20,
};
type Item = {
  name: string;
  age: number;
};
const toQuery = (item: Item) => {
  router.push({
    name: "AddArtical",
    query: item,
  });
};

如果要接收路由传递的参数,要使用useRoute(),注意:不是useRouter()

import { useRoute } from "vue-router";
const route = useRoute();
const { name, age } = route.query;
<div class="bg-cyan-300 w-full h-screen">{{ name }} {{ age }}</div>

params传参跳转只能用name,不能使用path

router.push({
    name: "AddArtical",
    params: item,
  });
const route = useRoute();
const { name, age } = route.params;

但是需要注意的是,params传参不会显示到url地址栏上,而且刷新后传递的值会被清除掉

所以我们可以使用动态路由参数,这样既能保护好传递的参数,又能让参数刷新不会被丢失

router/index.ts

  {
    name: "AddArtical",
    path: "/addartical/:id",
    component: () => import(`../components/AddContent/AddArtical.vue`),
  },

App.vue

import { useRouter } from "vue-router";
const router = useRouter();
const item = {
  id: 1,
  name: "kevin",
  age: 20,
};
type Item = {
  id: number;
  name: string;
  age: number;
};
const toQuery = (item: Item) => {
  router.push({
    name: "AddArtical",
    params: {
      id: item.id,
    },
  });
};

AddArtical.vue

const items = data.find((i: Item) => i.id === Number(route.params.id));
// 注意:因为router.params.id传过来的是string,而i.id是number,所以需要转换一下
<div class="bg-cyan-300 w-full h-screen">
  {{ items?.id }}
  {{ items?.name }}
  {{ items?.age }}
</div>
<!-- 因为是用的find查找,可能会找不到,所以要用 ? 来使其变量为可选 -->

嵌套路由

一些应用程序的 UI 由多层嵌套的组件组成。在这种情况下,URL 的片段通常对应于特定的嵌套组件结构(像vue文档这类的网站,在文档中有单独的子路由)

使用children属性

  {
    name: "Parent",
    path: "/parent",
    component: () => import(`../components/Demo/Parent.vue`),
    children: [
      {
        name: "Child1",
        path: "child1",
        component: () => import(`../components/Demo/Child1.vue`),
      },
      {
        name: "Child2",
        path: "child2",
        component: () => import(`../components/Demo/Child2.vue`),
      },
    ],
  },

Parent.vue

  <div class="bg-slate-400 h-screen">
    <RouterLink to="/parent/child1" class="btn btn-accent"
      >子组件1号</RouterLink
    >
    <RouterLink to="/parent/child2" class="btn btn-accent"
      >子组件2号</RouterLink
    >
    <RouterView></RouterView>
  </div>

Child1.vue/Child2.vue

<!-- 1内容 -->
<div class="">子组件1内容</div>
<!-- 2内容 -->
<div class="">子组件2内容</div>

命名视图

有时候想同时 (同级) 展示多个视图,而不是嵌套展示,例如创建一个布局,有 sidebar (侧导航) 和 main (主内容) 两个视图,这个时候命名视图就派上用场了。你可以在界面中拥有多个单独命名的视图,而不是只有一个单独的出口。如果 router-view 没有设置名字,那么默认为 default。

简单来说,命名视图可以在当前组件中插入多个<RouterView>

  {
    name: "Index",
    path: "/",
    component: () => import(`../components/Index/Index.vue`),
    children: [
      {
        path: "/parent1",
        components: {
          default: Child1,
        },
      },
      {
        path: "/parent2",
        components: {
          header: Child2,
          side: Child1,
        },
      },
    ],
  },
  <RouterView></RouterView>
  <RouterView name="header"></RouterView>
  <RouterView name="side"></RouterView>

重定向与别名

重定向

可以对一个路由默认的url地址进行指定url地址的跳转

在路由的对象中添加redirect属性,值可以是字符串(path),或者对象,如{path: '/user'}。又或者是用回调函数。

const routes: Array<RouteRecordRaw> = [
  {
    name: "Index",
    path: "/",
    redirect: "/parent1",
    component: () => import(`../components/Index/Index.vue`),
    children: [
      {
        path: "/parent1",
        components: {
          default: Child1,
        },
      },
      {
        path: "/parent2",
        components: {
          header: Child2,
          side: Child1,
        },
      },
    ],
  },
];

对象形式

redirect: { path: "./parent1" },

回调函数形式

    redirect: (v) => {
      return { path: "/parent1", query: v.query };
    },

别名 alias

重定向是指当用户访问 /home 时,URL 会被 / 替换,然后匹配成 /。那么什么是别名呢?

将 / 别名为 /home,意味着当用户访问 /home 时,URL 仍然是 /home,但会被匹配为用户正在访问 /。

{
    name: "Index",
    alias: ["/user", "/kk"],
    path: "/",
    component: () => import(`../components/Index/Index.vue`),
}

导航守卫

首先,导航守卫是在调用函数,传入参数为一个回调函数。这个回调函数的参数为to,from, next

to: 即将要进入的目标,from: 当前导航正要离开的路由,next为一个函数,是否进入目标路由。next(false)为不进入。

return false为取消当前导航

全局前置守卫

使用 router.beforeEach 注册一个全局前置守卫

router.beforeEach((to, from, next) => {
  next();
});

全局解析守卫

全局后置钩子

路由独享的守卫

可以直接在路由配置上定义 beforeEnter 守卫:

  {
    path: '/users/:id',
    component: UserDetails,
    beforeEnter: (to, from) => {
      // reject the navigation
      return false
    },
  },

组件内的守卫

router-link的active(选中改变样式)

在vue-router中要使用选中样式的方法有两种:

1、直接在路由js文件中配置linkActiveClass

const router = createRouter({
 linkActiveClass: "routerLinkActive",//routerLinkActive为index.css中写的class
 //...
});

2、在router-link中写入active-class

<RouterLink active-class="bg-primary">
相关文章
|
Java 索引
SpringBoot2.3.x整合ElasticSearch7.6.2 实现PDF,WORD全文检索
本文使用SpringBoot2.3.x + ElasticSearch7.6.2 实现对PDF,WORD进行全文检索 实现了对文件内容快速搜索
1833 0
SpringBoot2.3.x整合ElasticSearch7.6.2 实现PDF,WORD全文检索
|
7月前
|
存储 人工智能 Java
吃透 Spring AI Alibaba 多智能体|四大协同模式+完整代码
本文详细讲解 Spring AI Alibaba Multi-Agent 多智能体架构,包含顺序执行、并行执行、LLM 路由、监督者四大协同模式,搭配可运行代码示例与真实业务场景,从零带你上手多智能体开发。
3052 3
|
10月前
|
安全 网络架构
对比外部公网IP与局域网内部IP的差异性
综上所述,外部公网IP地址与局域网内部IP地址在功能、应用范围、安全性与管理方式上存在明显的差异性。公网IP地址为网络设备提供了在整个互联网中可识别的唯一身份,而内网IP仅在私有网络中有效,且安全性相对较高。理解这些差异能有助于更好地配合网络地址的规划、管理与安全策略的设计。
706 8
|
3月前
|
传感器 安全 数据可视化
沉浸式学习革命:VR虚拟培训让新员工上手速度提升3倍
随着工业4.0和数字化转型的深入,企业对技能型人才的需求日益增长。传统的新员工培训模式往往面临周期长、成本高、风险大以及实操机会稀缺等痛点。基于云计算、虚拟现实(VR)及增强现实(AR)技术的沉浸式培训方案,正在重塑企业的人才培养体系。通过构建高保真的数字孪生环境与实时交互系统,该方案不仅显著缩短了学习曲线,更实现了从“被动听讲”到“主动探索”的根本性转变。
|
2月前
|
JSON 监控 API
千问大模型API调用报错?10种常见原因与解决方案
千问大模型API调用遇到报错?本文汇总百炼API常见的10类错误(API Key无效、余额不足、限流、Token超限等),给出排查思路与解决方案,帮你快速恢复大模型API调用
959 0
|
3月前
|
弹性计算 Java 开发工具
阿里云国际站:OSS SDK上传文件报错?
开发者集成阿里云OSS SDK时,真正的难点往往不在业务逻辑,而在上传那一刻跳出的红色报错。InvalidAccessKeyId、SignatureDoesNotMatch、ConnectionTimeout……这些报错看似碎片化,实则每一次都指向Endpoint、AccessKey与配置项的耦合问题。阿里云OSS SDK上传文件报错排查,本质上是对三者关系的逐层还原。下面从最常见的报错类型切入,梳理几条被反复验证过的定位路径。
549 0
|
4月前
|
消息中间件 NoSQL API
反向海淘系统高并发秒杀实战:Redis+Lua分布式锁防超卖
Taocarts跨境电商秒杀系统采用Redis+Lua原子扣减、分布式锁防重、消息队列异步解耦,成功应对黑五大促瞬时高并发(QPS达8000),实现零超卖、响应降至80ms,保障大促稳定可靠。(239字)
339 0
|
4月前
|
人工智能 运维 数据挖掘
2026年SCRM价格指南:多少钱一年、怎么收费、怎么选不踩坑
SCRM价格从几千到几十万差在哪?本文拆解2026年SCRM收费标准、预算区间、长期成本和选型避坑,帮企业判断哪类系统真正适合自己,避免低价入坑、高价浪费。
421 0
|
7月前
|
SQL 弹性计算 供应链
年增50%门店,资源降本35%:「收钱吧·全来店」如何基于阿里云SelectDB重构餐饮数据底座?
全来店是收钱吧旗下数字化门店服务商,专注连锁餐饮SaaS。面对年增50%的万店规模挑战,其通过阿里云SelectDB Serverless重构数据底座,实现负载隔离与弹性伸缩,查询性能提升80%,成本降低35%,支撑全域实时经营监控与供应链精准核算。
657 2
年增50%门店,资源降本35%:「收钱吧·全来店」如何基于阿里云SelectDB重构餐饮数据底座?
|
7月前
|
数据可视化 API 定位技术
快递物流全生命周期解决方案API接口介绍
本文介绍快递物流全生命周期API解决方案,涵盖查询、轨迹订阅、地图可视化、地址解析、单号识别、价格/时效预估、网点查询、拦截、面单打印及签单回传等10+核心能力,助力开发者高效集成智能、低成本、高体验的物流服务。
488 0