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

vue3 子路由

作者:世界哪有真情   发布日期:2025-10-18   浏览:78

// 定义子路由的示例代码

// 1. 首先,确保你已经安装了 Vue Router 并在项目中引入它。

// 2. 创建一个 Vue Router 实例,并定义父路由和子路由。
import { createRouter, createWebHistory } from 'vue-router';
import ParentComponent from './components/ParentComponent.vue';
import ChildComponent1 from './components/ChildComponent1.vue';
import ChildComponent2 from './components/ChildComponent2.vue';

const routes = [
  {
    path: '/parent',
    component: ParentComponent,
    children: [
      {
        path: 'child1', // 子路由路径
        component: ChildComponent1,
      },
      {
        path: 'child2', // 子路由路径
        component: ChildComponent2,
      },
    ],
  },
];

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

// 3. 在父组件中使用 <router-view> 来渲染子路由组件。
// ParentComponent.vue
<template>
  <div>
    <h1>这是父组件</h1>
    <router-link to="/parent/child1">前往子组件1</router-link>
    <router-link to="/parent/child2">前往子组件2</router-link>
    <router-view></router-view> <!-- 渲染子路由组件 -->
  </div>
</template>

<script>
export default {
  name: 'ParentComponent',
};
</script>

// 4. 确保在 main.js 或入口文件中挂载路由实例。
import { createApp } from 'vue';
import App from './App.vue';
import router from './router'; // 假设你的路由配置文件在 ./router.js 中

createApp(App).use(router).mount('#app');

解释说明:

  • 父路由/parent 是父路由,指向 ParentComponent 组件。
  • 子路由/parent/child1/parent/child2 是子路由,分别指向 ChildComponent1ChildComponent2 组件。
  • <router-view>:在父组件中使用 <router-view> 来动态渲染匹配到的子路由组件。
  • <router-link>:用于创建导航链接,点击后会切换到对应的子路由。

上一篇:vue 图表组件

下一篇:vue3组件传值的方式

大家都在看

vue js for循环

vue.config.js 配置

vue.config.js configu

node.js vue

vue3组件传值的方式

vue3 子路由

vue 图表组件

vue3+vite+ts

vue3watch监听多个变量

vue查看版本

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

Laravel 中文站