首页
示例工具

vue的多种路由模式

Category:

Tags:

什么是vue-router

是页面应用用于设定访问路径,将路径和组件映射起来的路由插件

初始化路由

text
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router"; const routes: RouteRecordRaw[] = [ {   path: "/",   redirect: "/home", }, {   path: "/home",   component: () => import("../components/ACom.vue"), }, {   path: "/b/:id",   component: () => import("../components/BCom.vue"),   props: false, }, ]; const router = createRouter({ history: createWebHistory(), routes, }); export default router; ​

这边只说一下这个props

RouteRecordRaw的props

布尔模式

props 设置为 true 时,route.params 将被设置为组件的 props,默认围殴false。

对于有命名视图的路由,你必须为每个命名视图定义 props 配置

那么什么是命名视图呢?

官网上有描述

对象模式

依旧是设置成组件的props

text
props: { newsletterPopup: false }

函数模式

创建返回props的函数

text
{   path: "/home",   component: () => import("../components/ACom.vue"),   props: (route) => ({ query: route.query.q + 'hh' }), },

route.query便是路径的query,例如 访问 /home?q=abc 将会生产出一个prop {query:'abchh'}

路由的几种模式

hash模式

http://127.0.0.1:5174/#/home

#/home就是hash值

原理:通过原生的hashChange事件监听hash值的变化

H5模式(history模式)

和hash的表现方式一样但url上没有#

原理: 利用h5的history 的pushState()和replaceState()实现