【Vue.js】项目中 router-view 可以有几个?
在 Vue 项目中,router-view是一个用于渲染路由组件的组件。在一个应用程序中,可以多次使用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 路由的子路由。
更多推荐



所有评论(0)