Vue 菜单路由(router)只替换对应主页面中内容,而不是整个home页面的router index.js的两种设置方法

本文介绍了两种使用Vue.js实现前端路由的方式,通过设置路由及其children来动态替换主页面内容,保持菜单和标题栏不变。第一种方式是在路由配置中设置一个home路由,并将其他一级菜单作为其children,第二种方式则是每个一级菜单对应一个路由对象,组件都设置为布局组件,然后设置children来处理二级菜单。两种方法虽然原理相同,但在代码组织上有所不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在系统登录到系统主页面之后,通过点击不同的菜单动态在主页面内替换相应的内容,而保持菜单栏和标题栏内容不变,可以通过以下两种方式实现,两种方式的原理都是相同的,

方式一:在路由设置时,设置一个home路由,其compone对应的就是home组件,然后一级菜单对应的路由都作为其children[ ]进行设置,在home页面的 主界面(main)添加<router-view>,则在点击主界面的菜单栏跳转指定的router时,就会只替换home中添加<router-view>的位置,此操作相当于是把其他的组件都设置成了home组件的子组件。其他的需要进行全部显示页面替换的可以写成home路由并列的路由对象,例如:login,404等。

const routes = [
  {
    path: '/',
    redirect:'/login',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login/index.vue')
  },
  {
    path:'/home',
    name:'home',
    component: Home,
    redirect:'/welcome',
    // component:() => import('../views/Home/index.vue'),
    children:[
      {
        path:'/welcome',
        component:()=>import('../views/Home/Welcome/index.vue'),
      },
      {
        path:'/users',
        component:()=>import('../views/UserManage/UserManage.vue'),
      },
    ]
  },

方式二:其实原理是相同的,就是写法的不同而已。每个一级菜单对应一个路由对象,同时每个一级菜单对应路由的组件(component)都设置为home(Layout)组件,然后,其默认跳转到一个二级菜单路由,其所有的二级菜单都作为其children[ ],如果有三级菜单的话继续利用children[]进行。方法二的结构看起来更清晰,但是多写了些重复的代码。

import Layout from '../views/layout/Layout'

export const constantRouterMap = [
  { path: '/login', component: () => import('@/views/login/index'), hidden: true },
  { path: '/404', component: () => import('@/views/404'), hidden: true },

  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    name: 'Dashboard',
    hidden: true,
    children: [{
      path: 'dashboard',
      component: () => import('@/views/dashboard/index')
    }]
  },

  {
    path: '/example',
    component: Layout,
    redirect: '/example/table',
    name: 'Example',
    meta: { title: 'Example', icon: 'example' },
    children: [
      {
        path: 'table',
        name: 'Table',
        component: () => import('@/views/table/index'),
        meta: { title: 'Table', icon: 'table' }
      },
      {
        path: 'tree',
        name: 'Tree',
        component: () => import('@/views/tree/index'),
        meta: { title: 'Tree', icon: 'tree' }
      }
    ]
  },

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值