vue 遍历 router-view
在Vue中,使用<router-view />组件可以在应用程序的模板中渲染匹配当前URL的组件。<router-view />组件是Vue Router提供的用于显示路由组件的占位符。
要遍历<router-view />组件,你可以通过在路由配置中使用嵌套路由来实现。嵌套路由允许你在一个父级路由下定义子级路由,这样在父级路由组件的模板中就可以使用<router-view />来渲染子级路由组件。
以下是一个示例:
// 路由配置
const routes = [
{
path: '/parent',
component: Parent,
children: [
{
path: '',
name: 'DefaultChild',
component: DefaultChild
},
{
path: 'child1',
name: 'Child1',
component: Child1
},
{
path: 'child2',
name: 'Child2',
component: Child2
}
]
}
]
// 父级路由组件
const Parent = {
template: `
<div>
<h1>Parent Component</h1>
<router-view></router-view>
</div>
`
}
// 子级路由组件
const DefaultChild = {
template: '<div>Default Child Component</div>'
}
const Child1 = {
template: '<div>Child 1 Component</div>'
}
const Child2 = {
template: '<div>Child 2 Component</div>'
}
// 创建路由实例
const router = new VueRouter({
routes
})
// 创建Vue实例
new Vue({
router
}).$mount('#app')
在上面的示例中,Parent组件是父级路由组件,它的模板中包含一个<router-view></router-view>占位符。子级路由组件DefaultChild,Child1和Child2分别对应于父级路由的不同子路径。
当访问/parent路径时,Parent组件会被渲染,并且DefaultChild组件会作为子级路由的默认组件渲染到<router-view></router-view>中。当访问/parent/child1路径时,Child1组件会被渲染到<router-view></router-view>中。
通过这种方式,你可以在父级路由组件的模板中遍历子级路由组件,根据不同的路径渲染不同的组件内容
原文地址: https://www.cveoy.top/t/topic/i0VA 著作权归作者所有。请勿转载和采集!