首先要在自己的路由配置文件里面创建对应的路由
例如我的路由主页是routerindex
两个子路由分别是routerboy和routergirl- import Vue from 'vue'
- //1.引入路由
- import VueRouter from 'vue-router'
- import RouterIndex from '@/components/routerproject/routerindex'
- import routerboy from '@/components/routerproject/routerboy'
- import routergirl from '@/components/routerproject/routergirl'
- //2.安装路由
- Vue.use(VueRouter)
- //3.创建路由
- export default new VueRouter({
- routes:[
- {
- path:"/routerproject/routerindex",
- name:"routerindex",
- component:RouterIndex,
- children:[
- {
- path:"routerboy",
- name:"routerboy",
- component:routerboy
- },
- {
- path:"routergirl",
- name:"routergirl",
- component:routergirl
- }
- ]
- }
- ]
- })
复制代码
子路由需要在 VueRouter 的参数中使用 children 配置;
切记,在children 中,子路由的路径不要加 / ;
然后再看主路由页面routerindex的代码
1、首先要写入<router-view></router-view>添加路由视图
2、使用router-link并且写上子路由的位置路径,注意,这里就需要写上完整的路径
- <template>
- <div>
- <h3>路由首页</h3>
- <router-link to="/routerproject/routerindex/routerboy">跳转至儿子路由页面</router-link>
- <router-link to="/routerproject/routerindex/routergirl">跳转至女儿路由页面</router-link>
- <router-view></router-view>
- </div>
- </template>
- <script>
- export default {
- name: 'routerindex',
- props: {
- },
- data(){
- return{
- }
- }
- }
- </script>
- <style>
- </style>
复制代码
这是页面默认显示的样子,路径结尾是路由首页的路径
点击对应的跳转按钮,路径就会改变,页面上也会显示对应的路由页面显示的内容,如下图
如果想要直接显示【儿子路由】或者【女儿路由】,在路由配置文件中,添加redirect重定向即可- children:[
- {
- path:"",
- redirect:"routerboy"
- },
- {
- path:"routerboy",
- name:"routerboy",
- component:routerboy
- },
- {
- path:"routergirl",
- name:"routergirl",
- component:routergirl
- }
- ]
复制代码
|