Vue.js 中定义二级路由涉及三个步骤:首先创建父路由,指定嵌套子路由的 children 数组;然后在父路由的 children 数组中定义子路由;最后注册路由,使用 VueRouter 实例注册路由。

Vue.js 中定义二级路由
在 Vue.js 中,二级路由是指在嵌套路由结构中嵌套在父路由内的子路由。要定义二级路由,需要在父路由的 children 数组中定义它们。
具体步骤:
routes.js 文件中创建一个父路由,如下所示:<code class="javascript">const routes = [
{
path: '/parent-route',
component: ParentRouteComponent,
children: [], // 嵌套子路由的数组
},
];</code>children 数组中添加一个或多个子路由,如下所示:<code class="javascript">const routes = [
{
path: '/parent-route',
component: ParentRouteComponent,
children: [
{
path: 'child-route-1',
component: ChildRoute1Component,
},
{
path: 'child-route-2',
component: ChildRoute2Component,
},
],
},
];</code>VueRouter 实例注册路由:<code class="javascript">// main.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes.js';
Vue.use(VueRouter);
const router = new VueRouter({
routes,
});
const app = new Vue({
router,
}).$mount('#app');</code>示例:
立即学习“前端免费学习笔记(深入)”;
以下是一个带有二级路由的示例路由结构:
<code class="javascript">const routes = [
{
path: '/',
component: App,
children: [
{
path: 'home',
component: Home,
},
{
path: 'about',
component: About,
},
],
},
];</code>这样,就能在 /home 和 /about 路径下访问二级路由。
以上就是vue二级路由怎么定义的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号