Child routing in Vue.js allows you to define nested routes within a parent route, creating a hierarchical structure for your application's routing. This is useful when you have components that need their own set of routes, such as a nested navigation or subpages within a larger page.
To set up child routing in Vue.js, follow these steps:
- Define your parent route and configure it in your router:
// router.js
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent,
},
],
},
],
});
export default router;
In this example, we have a parent route with the path /parent
and the ParentComponent
. The children
property is an array that defines the child routes. In this case, we have a single child route with the path child
and the ChildComponent
.
- Create the parent and child components:
<!-- ParentComponent.vue -->
<template>
<div>
<h1>Parent Component</h1>
<router-view></router-view>
</div>
</template>
<!-- ChildComponent.vue -->
<template>
<div>
<h2>Child Component</h2>
<!-- Content for the child component -->
</div>
</template>
In the ParentComponent
template, we use the <router-view>
component to render the child routes. This acts as a placeholder that will be filled with the appropriate child component based on the current route.
- Render the parent component and configure the routing in your app:
<!-- App.vue -->
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<!-- main.js -->
import Vue from 'vue';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false;
new Vue({
router,
render: h => h(App),
}).$mount('#app');
In the App.vue
template, we render the <router-view>
component, which will be responsible for rendering the appropriate component based on the current route.
That's it! With these steps, you've set up child routing in Vue.js. When you navigate to /parent
, the ParentComponent
will be rendered, and when you navigate to /parent/child
, the ChildComponent
will be rendered within the ParentComponent
.
No comments:
Post a Comment