vue和React路由

目录

安装

浏览器路由模式

配置(/src/router/index.js )

路由表的配置字段 

Vue

命名路由(name)

命名视图(同级展示)

路由元信息(meta,任意附加信息,如授权)

传参

url参数

location属性值

window

useLocation()

query(显式)携带辅助信息

params(显式/隐式(刷新页面会消失))差异化界面 

动态路由(不同parmas,访问同一个组件)

编程式路由(非link模式)

默认路由(没有匹配成功 )、重定向路由(redirect/Navigate )、404(*/errorElement)

Vue

React

loader回调函数(路由前触发)

主入口

守卫(权限、路由拦截)

导航解析流程

全局

Vue

React

/src/components/BeforeEach.jsx

局部路由(相比组件路由,更推荐局部,更好地逻辑分块)

组件路由

浏览器输入URL展示路由对应组件

Vue占位router-view\router-link

React占位Outlet\Link

导航重复(修改原型方法)


路由:根据不同的url地址展示不同的内容,SPA(单页应用)的路径管理器

安装

Vue3搭配的是Vue Router4,其他用法上和vue2没有太大变化

//Vue.use() 方法进行安装和注册VueRouter插件
//自动调用插件对象中的 install 方法
Vue.use(VueRouter);

npm install vue-router

npm i react-router-dom

浏览器路由模式

  • history 模式使用浏览器的 History API,可以在 URL 中隐藏额外的字符,适合大多数常规的浏览器环境。
  • 不使用哈希符号 #,路由更加美观。
  • 可以充分利用浏览器的前进和后退功能。
  • 需要服务器配置支持,以确保在直接访问路由时返回正确的页面。
  • HTML5history API监听URL变化,所以有浏览器兼容问题
//Vue 2.x 或 3.x  Options API
const router = new VueRouter({
  mode: 'history',
  routes
});

// Vue 3.x  Composition API
import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
  history: createWebHistory(),
  routes
})
  • hash 模式在 URL 中使用哈希值( #,可以通过监听哈希变化来实现路由导航)
  • 不需要服务器配置支持(哈希值不会发送到服务器)
  • 适用于不支持 History API 或需要兼容旧版浏览器的情况。
  • 不充分利用浏览器的前进和后退功能,只有一个历史记录入口。
  • 通过window.addEventListener监听浏览器的onhashchange()事件变化,查找对应的路由规则
//Vue 2.x 或 3.x  Options API
const router = new VueRouter({
  mode: 'hash',
  routes
});

// Vue 3.x  Composition API
import { createRouter, createWebHashHistory} from 'vue-router';
const router = createRouter({
  history:  createWebHashHistory(),
  routes
})
  • 没有指定路由模式,它会根据当前的环境自动选择合适的模式。
const router = new VueRouter({
  routes
})

配置(/src/router/index.js )

路由表的配置字段 

  • path:指定路径

  • element(React)/component(Vue):对应组件

  • children:嵌套路由

Vue

命名路由(name)

 params 的自动编码/解码

{
        path: '/about/foo/:id',
        name: 'foo',
        component: Foo
}

{ name: 'foo', params: {id: 123} }

命名视图(同级展示)

路由元信息(meta,任意附加信息,如授权)

meta: { auth: false }
this.$route.meta.auth

import { useLocation, matchRoutes, Navigate } from 'react-router-dom'
import { routes } from '../../router';
export default function BeforeEach(props) {
  const location = useLocation();
  const matchs = matchRoutes(routes, location)
  const meta = matchs[matchs.length-1].route.meta
  if(meta.auth){
    return <Navigate to="/login" />
  }
  else{
    return (
      <div>{ props.children }</div>
    )
  }
}

传参

url参数

http://example.com/page?param1=value1&param2=value2#section1

分隔实际的URL和参数
& URL中指定的参数间的分隔符
= 左边为参数名、右边参数值
#

锚点(Anchor),用于标识文档中的特定位置或元素,

仅在客户端使用,并且由浏览器处理,不发送到服务器

指示浏览器滚动到具有 id="section1" 的元素处。

location属性值

window

window的全局对象,表示当前页面http://www.example.com/path/index.html

window.location.href:获取/设置 url

window.location.orgin:协议、主机名和端口号部分

//https://www.example.com:8080/page.html
//     ://               :
//https%3A%2F%2Fwww.example.com%3A8080。
encodeURIComponent(window.location.origin)
//encodeURIComponent用于将字符串中的特殊字符(空格、&、+、= 、?)转换为编码形式,确保URL中不包含任何无效字符



//查询参数时 或者 动态参数时 需要encodeURIComponent
const url = 'https://example.com/api?param=' + encodeURIComponent(queryParam);
window.location.href =`https://www.example.com/path/to/resource.html/domain=${location.host}&req=${encodeURIComponent(location.pathname)}&protocol=https${location.hash}`

window.location.protocol: 协议http

window.location.host:主机+端口(host:8080)/IP地址(127.123.32.1唯一)/域名(www.example.com助记)

window.location.hostname:主机host

window.location.port:端口8080

window.location.pathname: 资源路径path/index.html,资源index.html

window.location.hash:

window.location.search: 搜索

var searchParams = new URLSearchParams(window.location.search);
console.log(searchParams.get('name')); // 输出 "John"

useLocation()

import { useLocation } from 'react-router-dom'

  • hash:哈希值

  • key:唯一标识

  • pathname:路径

  • search:query值(需要把字符串解析成对象。)

  • state:隐式数据

query(显式)携带辅助信息

path: '/user/',

$route.query

import { useSearchParams } from 'react-router-dom'

  const [searchParams, setSearchParams] = useSearchParams()
  console.log( searchParams.get('age') );
  const handleClick = () => {
	setSearchParams({ age: 22 })
  }

params(显式/隐式(刷新页面会消失))差异化界面 

$route.params

显式:path: '/user/:id',

隐式:path: '/user/',

query显式    /workbenchConfiguration/upload?wpReleId=59

params显式 /workbenchConfiguration/upload/59

动态路由(不同parmas,访问同一个组件)

​import { Outlet, Link } from 'react-router-dom'
export default function About() {
	return (
        <div>
            <Link to="/about/foo/123">foo 123</Link> | <Link to="/about/foo/456">foo 456</Link>
        </div>
   	)
}
//...

{
    path: 'foo/:id',
    element: <Foo />
}

//...

import { useParams } from 'react-router-dom'
export default function Foo() {
  const params = useParams()
  return (
    <div>Foo, { params.id }</div>
  )
}
​
//Vue与React唯一不同
this.$route.params.id 

编程式路由(非link模式)

//vue
this.$router.push({
      path: `/about/foo/${id}`
 })
//react
import {useNavigate } from 'react-router-dom'

const navigate = useNavigate()
const handleClick= () => {
        navigate('/about/foo/123')
}
默认路由(没有匹配成功 )、重定向路由(redirect/Navigate )、404(*/errorElement)
Vue
import VueRouter from 'vue-router'

import Home from '@/views/Home.vue'
const About={template:'<div>About</div>'}

const routes: Array<any> = [
  {
    path: '/',
    redirect: '/workbenchConfiguration'
  },
  {
    path: '/404',
    meta: { title: '404' },
    component: () => import('@/views/404.vue')
  },
  { path: '*', redirect: '/404' }
]

const router = new VueRouter({
  routes
})
React
import { createBrowserRouter, createHashRouter } from 'react-router-dom'
//路由表
export const routes = [
// 默认路由
    {
        index: true,
        //重定向
        element: <Navigate to="/about/foo/123" />,
       //自带errorElement
       errorElement: <div>404</div>,
    },
//*局部404
  {
    path: '*',
 	element: <div>404</div>
  }
];
//路由对象
const router = createBrowserRouter(routes);
export default router;
loader回调函数(路由前触发)

默认同步,配合redirect做权限拦截。

{
    path: 'bar',
    element: <Bar />,
        //async,await异步,Promise用于表示一个异步操作的最终完成(或失败)及其结果值。
    loader: async() => {
        let ret = await new Promise((resolve)=>{
            setTimeout(()=>{
                resolve({errcode: 0})
            }, 2000)
        })
        return ret; 
    }
}

useLoaderData()获取loader函数返回的数据

import { useLoaderData } from 'react-router-dom'
export default function Bar() {
  const data = useLoaderData()
  console.log(data)
  return (
    <div>Bar</div>
  )

loader函数中是没有办法使用<Navigate>组件进行重定向操作的

{
    path: 'bar',
    element: <Bar />,
    loader: async() => {
        let ret = await new Promise((resolve)=>{
            setTimeout(()=>{
                resolve({errcode: Math.random() > 0.5 ? 0 : -1})
            }, 2000)
        })
        if(ret.errcode === 0){
            return ret;
        }
        else{
            return redirect('/login')
        }
    }
}
主入口
//index.js
import { RouterProvider } from 'react-router-dom'
import router from './router';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RouterProvider router={router}></RouterProvider>
  </React.StrictMode>
);

守卫(权限、路由拦截)

导航解析流程

  1. 导航被触发。

  2. 在失活的组件里调用 beforeRouteLeave 守卫。

  3. 调用全局的 beforeEach 守卫。

  4. 在重用的组件里调用 beforeRouteUpdate 守卫(2.2+)。

  5. 在路由配置里调用 beforeEnter

  6. 解析异步路由组件。

  7. 在被激活的组件里调用 beforeRouteEnter

  8. 调用全局的 beforeResolve 守卫(2.5+)。

  9. 导航被确认。

  10. 调用全局的 afterEach 钩子。

  11. 触发 DOM 更新。

  12. 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。

全局

Vue

//to
router.beforeEach((to, from, next)=>{
  if(to.meta.auth){
    next('/');
  }
  else{
    next();
  }
})
//vue+ts
router.beforeEach((to: any, from: any, next: any) => {
  const metaTitlt = (to.meta && to.meta.title) || ''
  document.title = `${metaTitlt} - 默认模版`
//是否从根路径而来,当前路由的来源路径和即将进入的路由的路径是否相同
  if (from.path !== '/' && from.matched[0].path !== to.matched[0].path) {
    message.destroy()
  }
  next()
})

React

/src/components/BeforeEach.jsx

import React from 'react'
import { Navigate } from 'react-router-dom'
import { routes } from '../../router';
export default function BeforeEach(props) {
  if(true){
    return <Navigate to="/login" />
  }
  else{
    return (
      <div>{ props.children }</div>
    )
  }
}
export const routes = [
  {
    path: '/',
    element: <BeforeEach><App /></BeforeEach>//包裹根组件APP
  }
]

局部路由(相比组件路由,更推荐局部,更好地逻辑分块)

const routes = [
    {
        name: 'bar',
        component: Bar,
        beforeEnter(to, from, next){
            if(to.meta.auth){
                next('/');
            }
            else{
                next();
            }
        }
    }
];

组件路由

<script>
  export default {
    name: 'FooView',
    beforeRouteEnter(to, from, next){
      if(to.meta.auth){
        next('/');
      }
      else{
        next();
      }
    }
  }
</script>

浏览器输入URL展示路由对应组件

没有占位的话,默认整个页面

Vue占位router-view\router-link

<template>
  <div>
    <router-link to="/">首页</router-link> | 
    <router-link to="/about">关于</router-link>
    <router-view></router-view>
  </div>
</template>

React占位Outlet\Link

​import React from "react";
import { Outlet, Link } from 'react-router-dom'
function App() {
  return (
    <div className="App">
      <h2>hello react</h2>
      <Link to="/">首页</Link> | <Link to="/about">关于</Link>
      <Outlet />
    </div>
  );
}
export default App;

带样式的声明式路由NavLink

导航重复(修改原型push、replace方法)

push:将新的路由添加到浏览器的历史记录中,这样用户就可以通过浏览器的后退按钮回到之前的路由。

this.$router.push('/about')

replace:不会在浏览器的历史记录中留下新的条目,而是直接替换当前的历史记录条目。

this.$router.replace('/contact')

比如在处理登录页面时,登录成功后可能会用replace方法替换当前路由,以防止用户通过后退按钮回到登录页面。

修改 VueRouter 的原型方法 pushreplace,用来捕获导航重复错误并进行处理,

不会在控制台中抛出错误,从而避免了不必要的错误提示和潜在的问题。

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      throw err;
    }
  });
};

const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      throw err;
    }
  });
};

const router = new VueRouter({
  // 路由配置...
});

export default router;

猜你喜欢

转载自blog.csdn.net/qq_28838891/article/details/131691290