【Vue.js】项目中 router-view 可以有几个?

在 Vue 项目中,router-view 是一个用于渲染路由组件的组件。在一个应用程序中,可以多次使用 router-view,以渲染多个不同的路由组件。

具体来说,router-view 只能渲染当前匹配到的路由组件。在使用 Vue Router 时,可以通过在路由配置中嵌套子路由来实现多个 router-view 的使用。

eg

./router/index.js

import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
import Contact from './views/Contact.vue'
import Profile from './views/Profile.vue'
import Settings from './views/Settings.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
    },
    {
      path: '/about',
      name: 'about',
      component: About,
    },
    {
      path: '/contact',
      name: 'contact',
      component: Contact,
    },
    {
      path: '/profile',
      name: 'profile',
      component: Profile,
      children: [
        {
          path: '',
          name: 'profile-settings',
          component: Settings,
        },
        {
          path: 'password',
          name: 'profile-password',
          component: Password,
        },
      ],
    },
  ],
})

在这个例子中,我们定义了四个路由,分别对应着不同的组件。其中,/profile 路由定义了一个嵌套的子路由,其包含两个子路由,分别对应着 Settings 组件和 Password 组件。如果我们在应用程序的模板中使用两个 router-view,eg:

html 页面 

<template>
  <div>
    <router-view></router-view>
    <router-view name="settings"></router-view>
  </div>
</template>

那么,当我们访问 /profile 路由时,第一个 router-view 会渲染 Profile 组件,第二个 router-view 会渲染 Settings 组件。当我们访问 /profile/password 路由时,第一个 router-view 仍然会渲染 Profile 组件,但是第二个 router-view 会渲染 Password 组件。

需要注意的是,如果使用多个 router-view,应该为每个 router-view 指定一个唯一的名称,以便在路由配置中正确地匹配子路由。在上面的例子中,我们为第二个 router-view 指定了一个名为 settings 的名称,以便匹配 /profile 路由的子路由。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值