Setting Up Vue Router for Nested Veiws
Configuring nested routes in Vue involves four key steps:
1. Router Configuration (router/index.js)
Define parent and child routes in your router configuraton:
import Vue from 'vue';
import Router from 'vue-router';
import MainLayout from '@/components/layout/MainLayout';
import UserList from '@/components/user/UserList';
import ResourceTable from '@/components/resources/ResourceTable';
import ExternalUserForm from '@/components/user/ExternalUserForm';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'MainLayout',
component: MainLayout,
children: [
{
path: '/users',
name: 'UserList',
component: UserList
},
{
path: '/resources',
name: 'ResourceTable',
component: ResourceTable
}
]
},
{
path: '/external-users',
name: 'ExternalUserForm',
component: ExternalUserForm
}
]
});
2. Main Application Setup (main.js)
Initialize Vue with router and required dependencies:
import Vue from 'vue';
import App from './App.vue';
import ElementUI from 'element-ui';
import router from './router';
import store from './store';
import 'element-ui/lib/theme-chalk/index.css';
import './assets/css/app.css';
Vue.config.productionTip = false;
Vue.use(ElementUI);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app');
3. Root Component (App.vue)
The main application component with router view:
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
};
</script>
<style>
#app {
width: 100%;
height: 100%;
}
</style>
The <router-view> in App.vue serves as the entry point for the root route configured at path: '/'.
4. Nested View Implementation
Parent componant with nested router view:
<template>
<div>
<el-container>
<el-aside width="220px">
<el-tree
:data="treeData"
node-key="id"
:props="treeProps"
:highlight-current="true"
@node-click="onTreeNodeClick">
<span class="tree-node" slot-scope="{ node, data }">
<span>{{ data.label }}</span>
<span>
<el-button type="text" size="mini">
<i class="el-icon-edit"></i>
</el-button>
<el-button type="text" size="mini">
<i class="el-icon-plus"></i>
</el-button>
<el-button type="text" size="mini">
<i class="el-icon-delete"></i>
</el-button>
</span>
</span>
</el-tree>
</el-aside>
<el-main>
<el-col :span="24" class="content-area">
<transition name="fade-transform" mode="out-in">
<router-view></router-view>
</transition>
</el-col>
</el-main>
</el-container>
</div>
</template>
The nested <router-view> in el-main defines where child route components will be rendered.
Programmatic Navigation
Navigate to child routes programmatically:
methods: {
onTreeNodeClick(nodeData) {
this.selectedDomain = nodeData.domainId;
this.selectedOwner = nodeData.ownerId;
this.validateSelection();
this.$router.push({
path: this.targetRoute,
query: {
domainId: this.selectedDomain,
ownerId: this.selectedOwner
}
});
}
}