Vue3路由——基本使用、动态路由、路由正则、重复参数、嵌套路由、编程式导航、命名路由、重定向、别名、路由模式与导航守卫

news2025/7/17 11:04:44

文章目录

P23 Vue3路由的基本使用

npm init vite-app projectname
cd projectname
yarn
yarn add vue-router@4 --save

本视频不全,所以去看了晓舟老师的手把手教你学Vue3-路由基础-页面跳转的视频

App.vue

<template>
  <router-link to="/home">首页</router-link>
  <router-link to="/blog">博客</router-link>

  <!-- 切换页面 显示占位 -->
  <router-view></router-view>
</template>

<script>
export default {
  name: "App",
};
</script>

router/index.js

import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../components/Home.vue'
import Blog from '../components/Blog.vue'

const routes = [
    { path: '/home', component: Home },
    { path: '/blog', component: Blog },
]

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

export default router

main.js

import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app')

P24 动态路由和404NotFound

动态路由

个人认为老师讲的不太详细,看完老师的这一节后,又去看了晓舟老师的手把手教你学Vue3-路由传参(动态路由)

列表页直接到详情页 (没有公共的部分)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SMRNiTzm-1668577479177)(C:\Users\张丽君\Pictures\堆糖\动态路由.gif)]

App.vue

<template>
  <router-view></router-view>
</template>

<script>
export default {
  name: "App",
};
</script>

router/index.js

import { createRouter, createWebHashHistory } from 'vue-router'
import List from '../components/List.vue'
import Blog from '../components/Blog.vue'

const routes = [
    { path: '/', component: List },
    { path: '/blog/:id', component: Blog },
]

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

export default router

List.vue

<template>
  <h1>列表</h1>
  <ul>
    <li v-for="item in blogList" :key="item.id">
      <router-link :to="'/blog/' + item.id">{{ item.title }}</router-link>
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      // 真实开发中 数据是从后台拿来的
      blogList: [
        { id: 1, title: "html css" },
        { id: 2, title: "JavaScript " },
        { id: 3, title: "Vue" },
        { id: 4, title: "Node" },
        { id: 5, title: "React" },
      ],
    };
  },
};
</script>

Blog.vue

<template>
  <h1>博客详情: {{ $route.params.id }}</h1>
  <p>{{ blogCount }}</p>
</template>

<script>
export default {
  data() {
    return {
      blogCount: "",
    };
  },
  created() {
    let id = this.$route.params.id;
    this.getBlogDataById(id);
  },
  // 通过id到后台拿数据 现在没后台 模拟一下
  methods: {
    getBlogDataById(id) {
      switch (id) {
        case "1":
          this.blogCount = "结构与样式";
          break;
        case "2":
          this.blogCount = "原生jsyyds";
          break;
        case "3":
          this.blogCount = "框架节省代码";
          break;
        case "4":
          this.blogCount = "前后端数据交互";
          break;
        case "5":
          this.blogCount = "另一个框架";
          break;
      }
    },
  },
};
</script>

404NotFound

NotFound.vue

<template>
  <h1 style="text-align: center">404 NotFound</h1>
</template>

router.js

import { createRouter, createWebHashHistory } from 'vue-router'
import NotFound from '../components/NotFound.vue'

const routes = [
    { path: '/:path(.*)', component: NotFound }
]

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

export default router

p25 路由正则与重复参数

路由正则

router/index.js

import { createRouter, createWebHashHistory } from 'vue-router'
import NotFound from '../components/NotFound.vue'
import Article from '../components/Article.vue'

const routes = [
    { path: '/article/:id(\\d+)', component: Article },
    { path: '/:path(.*)', component: NotFound }
]

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

export default router

Article.vue

<template>
  <h1>Article页面{{ $route.params.id }}</h1>
</template>

在这里插入图片描述

重复参数

参考文档:https://router.vuejs.org/zh/guide/essentials/route-matching-syntax.html#%E5%8F%AF%E9%87%8D%E5%A4%8D%E7%9A%84%E5%8F%82%E6%95%B0

在这里插入图片描述

import { createRouter, createWebHashHistory } from 'vue-router'
import Film from '../components/Film.vue'
const routes = [
    { path: '/film/:id+', component: Film },
]
const router = createRouter({
    history: createWebHashHistory(),
    routes
})
export default router
<template>Film{{ $route.params.id }}</template>

p26 嵌套路由

路由里面再使用路由
在这里插入图片描述

index.js

import { createRouter, createWebHashHistory } from 'vue-router'

import User from '../components/User.vue'
import HengBan from '../components/HengBan.vue'
import ShuBan from '../components/ShuBan.vue'

const routes = [
    {
        path: '/user',
        component: User,
        children: [
            {
                path: 'hengban', component: HengBan
            },
            {
                path: 'shuban', component: ShuBan
            }
        ]
    }
]

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

export default router

User.vue

<template>
  <h1>User页面</h1>
  <router-view></router-view>
</template>

HengBan.vue

<template><h2>横版页面</h2></template>

p27 使用js跳转页面(编程式导航)

之前可以使用<router-link to='/'><router-link>

参考文档——编程式导航

Page.vue

<template>
  <h1>page页面</h1>
  <button @click="goPage">跳转页面</button>
</template>

<script>
export default {
  methods: {
    goPage() {
      // 这里我的/ 页面是List页面
      //   this.$router.push("/");
      //   this.$router.push({ path: "/user" });
      // 携带参数跳转
      //   this.$router.push({ path: "/blog/1" });
      //   this.$router.push({ name: "blog", params: { id: 2 } });
      this.$router.push({ path: "/", query: { search: "你好" } }); // ?search=你好
    },
  },
};
</script>

index.js

import { createRouter, createWebHashHistory } from 'vue-router'
import List from '../components/List.vue'
import Blog from '../components/Blog.vue'
import NotFound from '../components/NotFound.vue'

import User from '../components/User.vue'
import HengBan from '../components/HengBan.vue'
import ShuBan from '../components/ShuBan.vue'
import Page from '../components/Page.vue'

const routes = [
    { path: '/', component: List },
    { path: '/blog/:id', component: Blog, name: 'blog' },
    { path: '/:path(.*)', component: NotFound },
    {
        path: '/user',
        component: User,
        children: [
            {
                path: 'hengban', component: HengBan
            },
            {
                path: 'shuban', component: ShuBan
            }
        ]
    },
    {
        path: '/page',
        component: Page
    }
]

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

export default router

p28 命名路由与重定向别名

router.replace router.go

router.replace替换页面 前进后退 不能再用

router.go前进或者后退一页

<template>
  <h1>page页面</h1>
  <button @click="replacePage">替换页面</button>
  <button @click="$router.go(1)">前进</button>
  <button @click="$router.go(-1)">后退</button>
</template>

<script>
export default {
  methods: {
    replacePage() {
      this.$router.replace({ path: "/", query: { search: "你好" } });
    },
  },
};
</script>

命名路由

import { createRouter, createWebHashHistory } from 'vue-router'

import Shop from '../components/Shop.vue'
import LeftSideBar from '../components/LeftSideBar.vue'
import RightSideBar from '../components/RightSideBar.vue'
const routes = [
    {
        path: '/shop',
        components: {
            default: Shop,
            LeftSideBar,
            // 它们与 `<router-view>` 上的 `name` 属性匹配
            RightSideBar
        }
    }
]

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

export default router

App.vue

<template>
  <router-view name="LeftSideBar"></router-view>
  <router-view></router-view>
  <router-view name="RightSideBar"></router-view>
</template>

在这里插入图片描述

重定向

{
    path: '/mall',
    redirect: '/shop'
}

别名

const routes = [{ path: '/', component: Homepage, alias: '/home' }]

p29 路由模式与导航守卫

hash 路由兼容更好,但是带#显得丑些, histroy 和正常 url 路径一样,但是需要在服务器进行单独配置。
hash 模式是用 createWebHashHistory() 创建的: 
用 createWebHistory() 创建 HTML5 模式,推荐使用这个模式:
import { createRouter, createWebHashHistory } from 'vue-router'
import Page from '../components/Page.vue'

const routes = [
    {
        path: '/page',
        component: Page,
        // 路由级别的导航守卫
        beforeEnter: (to, from, next) => {
            // ...
        }
    },

]
const router = createRouter({
    history: createWebHashHistory(),
    routes
})
// 全局注册前置守卫
router.beforeEach((to, from, next) => {

})

export default router
<template>
  <h1>User页面</h1>
  <router-view></router-view>
</template>

<script>
export default {
  // 组件内部的导航守卫
  beforeEnter: (to, from, next) => {
    // ...
    // next(false);
      console.log('路由进入组件')
    next();
  },
    
    beforeRouteUpdate(){
        console.log('路由更新组件')
    },

  //离开当前的路由 可以在离开时做一个响应的判断 看是否离开
  beforeRouteLeave(to, from, next) {
      console.log('路由离开组件')
    next();
  },
};
</script>

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

[附源码]java毕业设计基于的花店后台管理系统

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

《Nature》STING 与 cGAMP 结合导致 TBK1 激酶募集和活化

来自细菌或病毒的核酸在受感染的细胞中会产生强效的免疫反应&#xff0c;而病原体衍生核酸的检测是宿主感知感染并启动保护性免疫反应的核心策略。cGAS (Cyclic GMP-AMP synthase) 是一种双链 DNA 传感器&#xff0c;可催化 cGAMP&#xff08;cyclic GMP-AMP&#xff09;的合成…

中间件简介

中间件简介 1. 中间件概述 随着网络和软件技术的飞速发展&#xff0c;软件面临更多的问题&#xff0c;例如&#xff1a;不同的操作系统、不同的网络环境等。在每个软件中解决这些问题加大了软件开发人员的负担&#xff0c;因此倾向于将这些具有广泛应用的共性功能提取出来&am…

【离散数学】第二章 测试

1.单选题 谓词推理要 A. 先US&#xff0c;后ES B. 先ES&#xff0c;后US 正确答案&#xff1a; B 2.单选题 前提: (∀x)(F(x)→G(x))&#xff0c;(∃x)F(x)&#xff0c; 结论: (∃x)G(x)。 A. 成立 B. 不成立 正确答案&#xff1a; A 3.单选题 根据ES规则&#xff0c;若(∃x)P(…

gRPC(八)生态 grpc-gateway 应用:同一个服务端支持Rpc和Restful Api

目录前言一、gRPC-Gateway概述1、简述2、出现二、准备工作1、目录结构2、环境准备1&#xff09;Protobuf2&#xff09;gRPC3&#xff09;gRPC-Gateway3、编写 IDL1&#xff09;google.api2&#xff09;hello.proto3&#xff09;编译proto4、制作证书1&#xff09;生成CA根证书2…

香港服务器一定比美国服务器好吗?

香港服务器一定比美国服务器好吗?从出海业务兴起以来就有不少的站长拿较为热门的香港服务器和美国服务器来作出对比&#xff0c;对其两者孰优孰劣的探讨一直都没有停止过。在这里&#xff0c;我们对两者做个比较。 香港服务器和美国服务器两者的对比&#xff1a; 1. 香港服务器…

linux笔记(3):东山哪吒STU开发板初体验

文章目录1.开发板上电观察串口1.1 从nand flash启动1.2 从SD卡启动2.上传文件到开发板2.1 使用FileZilla软件连接开发板2.2 使用ADB软件双11下单后&#xff0c;经过多日的等待&#xff0c;终于在昨天下午收到了开发板。在等待的过程中&#xff0c;看了一下文档和B站东山老师的视…

Rhino Linux:滚动发布但也很稳定的 Ubuntu

导读滚动发布的 Ubuntu 发行版&#xff1f;等等&#xff0c;什么&#xff1f; Rhino Linux 听起来不错……Ubuntu but rolling but also stable! Thats what Rhino Linux aims to be Rhino Linux 将成为 Rolling Rhino Remix 的继任者。这个由 http.llamaz 构建的 Linux 发行版…

01 Jenkins CICD 之 Git 命令使用

1. 前言 由于项目没有外网&#xff0c;需要在内网打镜像。但自己对git 还不是太熟悉。看着pipline 一脸的懵。所有针对git 命令在工作中常用的参数及用法简单学习记录下 git 技能树链接 2. git 常用参数 2.1 git全局设置 git config --global user.name "xxxxx" …

STC51单片机27——控制无刷电机

编写程序控制电调&#xff1a; #include<reg52.h> sbit PpmP2^0; sbit UpP2^1; sbit DownP2^2; sbit Led_UpP2^3; sbit Led_DownP2^4; unsigned char k0; unsigned char a0; void Control() { if(Up0&am…

云原生网关的可观测性体系实践

作者&#xff1a;井轶 概述 可观测性一词来源于控制理论&#xff0c;是指系统可以由其外部输出推断其其内部状态的程度&#xff0c;随着 IT 行业几十年的发展&#xff0c;IT 系统的监控、告警、问题排查等领域的逐渐成熟&#xff0c;IT 行业也将其抽象形成了一整套可观测性工…

Linux基础学习记录

LInux学习 文章目录LInux学习1. Linux快捷键2. Shell基本命令”*“&#xff0c;”&#xff1f;“&#xff0c;”[]“&#xff1a;通配符pwd&#xff1a;显示当前目录cd&#xff1a;改变目录ls&#xff1a;列出目录内容cat和more&#xff1a;查看文本文件catmorehead和tail&…

为什么C语言需要指定平台开发?

前言&#xff1a; 笔者心血来潮&#xff0c;特意站在初学者角度去思考为什么C语言需要指定平台去开发呢&#xff1f; 物有本末&#xff0c;事有终始&#xff0c;知其先后&#xff0c;则近道矣。 语言历史&#xff1a; 读者应该能明白程序最底层无非就是01010101二进制被CPU给调…

(续)SSM整合之springmvc笔记(SpringMVC获取请求参数)(P131-135)

目录 一 通过ServletAPI获取 1 . 新建TestParamController类 2 . index.html 3 . 在TestParamController类里面写getParamByServletAPI 4. 测试 重新部暑 二 通过控制器方法的形参获取请求参数 1 . index.html 2 . TestParamController 3. 测试 三 RequestPar…

Vue2.0开发之——Vue基础用法-事件绑定$event(20)

一 概述 事件参数对象$event表示事件参数对象event事件修饰符 二 事件参数对象 2.1 说明 在原生的 DOM 事件绑定中&#xff0c;可以在事件处理函数的形参处&#xff0c;接收事件参数对象 event 2.2 示例 布局代码 <button v-on:click"addCount">1</bu…

高光谱解混和图片去噪(Matlab代码实现)

&#x1f468;‍&#x1f393;个人主页&#xff1a;研学社的博客 &#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜…

使用id限定优化mysql分页查询limit偏移量大问题

在工作中可能偶尔会遇到&#xff0c;当使用limit实现分页查询时&#xff0c;当limit的偏移量越大时&#xff0c;sql语句的耗时也越大。 如图&#xff1a; 偏移量为0时&#xff0c;sql语句耗时在35毫秒。 顺便说下偏移量与页码、页大小的关系&#xff1a; 偏移量 (页码 - 1…

Spark的内存管理机制

在执行Spark 的应用程序时&#xff0c;Spark 集群会启动 Driver 和 Executor 两种 JVM 进程&#xff0c;前者为主控进程&#xff0c;负责创建 Spark 上下文&#xff0c;提交 Spark 作业&#xff08;Job&#xff09;&#xff0c;并将作业转化为计算任务&#xff08;Task&#xf…

深度学习基础--神经网络(1)激活函数

文章目录从感知机到神经网络激活函数阶跃函数&#xff08;感知机的激活函数&#xff09;sigmoid函数阶跃函数和sigmoid函数绘制和对比ReLU函数本文为学习笔记参考书籍&#xff1a;《深度学习入门 : 基于Python的理论与实现 》/ (日) 斋藤康毅著 ; 陆宇杰译. – 北京 : 人民邮电…

根据水声和摄影测量数据建立数字测深模型

无人船和无人车正越来越多地用于水深地形测量。使用这些平台采集数据的技术得到普遍的应用&#xff0c;但数据的融合仍然需要深入研究&#xff0c;其融合方法通常依赖于所使用的传感器和测量区域的特性。本文提出了一种融合无人艇&#xff08;USV&#xff09;和无人机&#xff…