Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3路由重定向

作者:此甥孓狠善良   发布日期:2026-04-20   浏览:74

// vue3路由重定向示例代码

import { createRouter, createWebHistory } from 'vue-router';

// 定义路由组件
const Home = { template: '<div>Home</div>' };
const About = { template: '<div>About</div>' };
const RedirectedPage = { template: '<div>Redirected Page</div>' };

// 创建路由实例
const routes = [
  {
    path: '/',
    redirect: '/home' // 访问根路径时重定向到/home
  },
  {
    path: '/home',
    component: Home
  },
  {
    path: '/about',
    component: About
  },
  {
    path: '/redirect',
    redirect: to => {
      // 动态重定向,根据条件选择重定向目标
      if (to.query.redirect) {
        return `/redirected-page?from=${to.query.from}`;
      }
      return '/home';
    }
  },
  {
    path: '/redirected-page',
    component: RedirectedPage
  }
];

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

export default router;

解释说明:

  1. 静态重定向

    • 在路由配置中使用 redirect 属性可以直接指定重定向的目标路径。例如,访问根路径 / 时会自动重定向到 /home
  2. 动态重定向

    • 使用函数形式的 redirect 可以根据条件动态决定重定向的目标路径。例如,访问 /redirect 路径时,可以根据查询参数 redirect 的存在与否来决定最终重定向到哪个页面。
  3. 创建路由实例

    • 使用 createRoutercreateWebHistory 来创建一个 Vue Router 实例,并将定义好的路由规则传递给它。
  4. 导出路由实例

    • 最后将创建好的路由实例导出,以便在主应用中使用。

上一篇:arco vue

下一篇:vue页面滚动到指定位置

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站