学习vue Router 一 起步,编程式导航,历史记录,路由传参

目录

起步,安装

[1. 安装](#1. 安装)

[2. 使用](#2. 使用)

命名路由

编程式导航

[1. 字符串模式](#1. 字符串模式)

[2. 对象模式](#2. 对象模式)

[3. 命名路由模式](#3. 命名路由模式)

历史记录

replace的使用

横跨历史

路由传参

[1. query路由传参](#1. query路由传参)

[2. 动态路由传参](#2. 动态路由传参)

[3. 二者的区别](#3. 二者的区别)


起步,安装

router 路由

因为vue是单页应用不会有那么多html 让我们跳转 所有要使用路由做页面的跳转

Vue 路由允许我们通过不同的 URL 访问不同的内容。通过 Vue 可以实现多视图的单页Web应用

1. 安装

使用Vue3 安装对应的router4版本

使用Vue2安装对应的router3版本

 npm install vue-router -s

2. 使用

在src目录下新建router文件夹,新建index.ts文件

TypeScript 复制代码
import {createRouter,createWebHistory,RouteRecordRaw} from "vue-router";

const routes:Array<RouteRecordRaw> = [
    {
        path: '/',
        component: () => import("../components/A.vue")
    },
    {
        path: "/card",
        component: () => import("../components/Card.vue")
    }
]

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

export default router

路由数组的类型 RouteRecordRaw

路由模式

  1. vue2 mode history vue3 createWebHistory

  2. vue2 mode hash vue3 createWebHashHistory

  3. vue2 mode abstact vue3 createMemoryHistory

1为history模式,原理是调用h5的history方法,2为hash模式,原理为调用location.hash进行跳转

router-link

请注意,我们没有使用常规的 a 标签,而是使用一个自定义组件 router-link 来创建链接。这使得 Vue Router 可以在不重新加载页面的情况下更改 URL,处理 URL 的生成以及编码。我们将在后面看到如何从这些功能中获益。

通过props to来进行跳转

默认渲染为一个a标签,

TypeScript 复制代码
<script setup lang='ts'>

</script>

<template>
  <h1>app组件</h1>
  <router-link to="/">A组件</router-link>
  <router-link to="/card">Card组件</router-link>
  <router-view></router-view>
</template>

<style scoped>

</style>

main.ts进行挂载

TypeScript 复制代码
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router"

const app = createApp(App)

app.use(router)

app.mount('#app')

直接通过a href也可以跳转但是会刷新页面

<a href="/reg">rrr</a>

命名路由

除了 path 之外,你还可以为任何路由提供 name。这有以下优点:

  • 没有硬编码的 URL
  • params 的自动编码/解码。
  • 防止你在 url 中出现打字错误。
  • 绕过路径排序(如显示一个)
TypeScript 复制代码
const routes:Array<RouteRecordRaw> = [
    {
        path: '/',
        name: "A",
        component: () => import("../components/A.vue")
    },
    {
        path: "/card",
        name: "card",
        component: () => import("../components/Card.vue")
    }
]

router-link跳转方式需要改变 变为对象并且有对应name

TypeScript 复制代码
<router-link :to="{name: 'A'}" style="margin-right: 10px">A组件</router-link>
  <router-link :to="{name: 'card'}">Card组件</router-link>

编程式导航

除了使用 <router-link> 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。

1. 字符串模式

TypeScript 复制代码
<script setup lang='ts'>
import {useRouter} from "vue-router";
const router = useRouter()
function toAny(url:string) {
  router.push(url)
}
</script>

<template>
  <h1>app组件</h1>
<!--  <router-link :to="{name: 'A'}" style="margin-right: 10px">A组件</router-link>-->
<!--  <router-link :to="{name: 'card'}">Card组件</router-link>-->
  <button @click="toAny('/')">toA</button>
  <button @click="toAny('/card')">ToCard</button>
  <router-view></router-view>
</template>

<style scoped>

</style>

2. 对象模式

复制代码
function toAny(url:string) {
  router.push({
    path: url
  })
}

3. 命名路由模式

复制代码
function toAny(url:string) {
  router.push({
    name: url
  })
}

历史记录

replace的使用

采用replace进行页面的跳转会同样也会创建渲染新的Vue组件,但是在history中其不会重复保存记录,而是替换原有的vue组件;

router-link的使用方法

TypeScript 复制代码
<router-link replace :to="{name: 'A'}" style="margin-right: 10px">A组件</router-link>
  <router-link replace :to="{name: 'card'}">Card组件</router-link>

编程式导航的用法

复制代码
function toAny(url:string) {
  router.replace({
    name: url
  })
}

横跨历史

该方法采用一个整数作为参数,表示在历史堆栈中前进或后退多少步

TypeScript 复制代码
 <button @click="next">前进</button>
 <button @click="prev">后退</button>
TypeScript 复制代码
const next = () => {
  //前进 数量不限于1
  router.go(1)
}
 
const prev = () => {
  //后退
  router.back()
}

路由传参

1. query路由传参

编程式导航 使用router push 或者 replace 的时候 改为对象形式新增query 必须传入一个对象

TypeScript 复制代码
<script setup lang="ts">
import {data} from "./data.json"
import {useRouter} from "vue-router";
const router = useRouter()
type Data = {
  id: number
  name: string
  address: string
}
function toDetails (item:Data) {
  router.push({
    path: "/B",
    query: item
  })
}
</script>

<template>
  <div class="container">
    <h1>这是内容区域</h1>
    <hr>
    <table class="table">
      <thead>
        <tr>
          <th>编号</th>
          <th>姓名</th>
          <th>地址</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in data" :key="item.id">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.address}}</td>
          <td><button @click="toDetails(item)">编辑</button></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
.table {
  width: 50%;
  border-collapse: collapse;
  border: 1px solid #ccc;
  margin: 0 auto;
  text-align: center;
}
th,td {
  border: 1px solid grey;
}
</style>

接受参数

使用 useRoute 的 query

TypeScript 复制代码
<script setup generic="T" lang="ts">
import {useRoute,useRouter} from "vue-router";
const route = useRoute()
const router = useRouter()
</script>

<template>
<div>
  <h1>我是b组件</h1>
  <button @click="router.back()">返回</button>
  <hr>
  <div>姓名:{{route.query.name}}</div>
  <div>地址:{{route.query.address}}</div>
  <div>编号:{{route.query.id}}</div>
</div>
</template>

<style scoped>

</style>

2. 动态路由传参

很多时候,我们需要将给定匹配模式的路由映射到同一个组件。例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但用户 ID 不同。在 Vue Router 中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数

router/index.ts

复制代码
{
    path: "/B/:id",
    name: "B",
    component: () => import("../components/B.vue")
}

使用params就必须使用name 的形式

复制代码
function toDetails (item:Data) {
  router.push({
    name: "B",
    params: {
      id: item.id
    }
  })
}
TypeScript 复制代码
<script setup generic="T" lang="ts">
import {useRoute,useRouter} from "vue-router";
import {data} from "./data.json"
type Data = {
  id: number
  name: string
  address: string
}
const route = useRoute()
const router = useRouter()
const item:Data = data.find(v => v.id === Number(route.params.id)) as Data
</script>

<template>
<div>
  <h1>我是b组件</h1>
  <button @click="router.back()">返回</button>
  <hr>
  <div>姓名:{{item.name}}</div>
  <div>地址:{{item.address}}</div>
  <div>编号:{{route.params.id}}</div>
</div>
</template>

<style scoped>

</style>

3. 二者的区别

  1. query 传参配置的是 path,而 params 传参配置的是name,在 params中配置 path 无效

  2. query 在路由配置不需要设置参数,而 params 必须设置

  3. query 传递的参数会显示在地址栏中

  4. params传参刷新会无效,但是 query 会保存传递过来的值,刷新不变 ;

  5. 路由配置

相关推荐
小游鱼KF6 分钟前
Spring学习前置知识
java·学习·spring
mez_Blog35 分钟前
个人小结(2.0)
前端·javascript·vue.js·学习·typescript
Rookie也要加油36 分钟前
WebRtc一对一视频通话_New_peer信令处理
笔记·学习·音视频·webrtc
珊珊而川43 分钟前
【浏览器面试真题】sessionStorage和localStorage
前端·javascript·面试
森叶1 小时前
Electron 安装包 asar 解压定位问题实战
前端·javascript·electron
David猪大卫1 小时前
数据结构修炼——顺序表和链表的区别与联系
c语言·数据结构·学习·算法·leetcode·链表·蓝桥杯
honey ball1 小时前
仪表放大器AD620
运维·单片机·嵌入式硬件·物联网·学习
深情废杨杨1 小时前
前端vue-插值表达式和v-html的区别
前端·javascript·vue.js
GHUIJS1 小时前
【vue3】vue3.3新特性真香
前端·javascript·vue.js
markzzw1 小时前
我在 Thoughtworks 被裁前后的经历
前端·javascript·面试