33、vue 中 命名视图的用法(二)

一般情况下,一个页面里面可能有多个组件,比如侧边栏,内容区,侧边栏是一个组件、内容区是一个组件,我们普遍会将两个组件作为子组件添加到主页面中,因为页面中只有一个

router-view视图,那么问题来了,怎么让一个页面中有多个视图呢,拥有多个视图,很随意,多写几个router-view标签就行了,但是每个router-view视图里面显示的相同的内容,这是一个问题,多写几个视图好像没什么用,那么怎么让一个页面中的多个视图显示不同的内容呢?

下面就来介绍命名视图的作用,首先,一般情况下,我们在路由配置中,一个路由路径只能对应一个组件,若想对应多个组件,必须得作为子组件存在,然后再一个公用的视图内显示,这是一个路由对应多个组件,这些组件对应一个视图

例如:

{
  path:'tv',
  name:'tv',
  component:Tv,
  children:[
    {path:'',component:Zhonghe},
    {path:'zhonghe',component:Zhonghe},
    {path:'guochan',component:Guochan},
    {path:'yingmei',component:Yingmei},
    {path:'riju',component:Riju},
    {path:'hanju',component:Hanju}
  ]
},

那么,下面来介绍命名视图:有时候想同时 (同级) 展示多个视图,而不是嵌套展示,例如创建一个布局,有 sidebar (侧导航) 和 main (主内容) 两个视图,这个时候命名视图就派上用场了。你可以在界面中拥有多个单独命名的视图,而不是只有一个单独的出口。如果 router-view 没有设置名字,那么默认为 default。






一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。确保正确使用 components配置 (带上 s):

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    }
  ]
})

解释一下:
在这个默认路由下,
第一个非未命名视图显示Foo组件
第二个name名为a的视图显示
Bar
组件
第二个name名为b的视图显示Baz组件

然后自己有些了个demo


router配置:

routes: [
  {
    path: '/',
    name: 'HelloWorld',
    component: HelloWorld,
    children:[
      {
        path:'',
        components:{
          default:List1,
          a:List2,
          b:List3
        }
      },
      {
        path:'list1',
        components:{
          default:List1,
          a:List2,
          b:List3
        }
       },
       {
        path:'list2',
        components:{
          default:List2,
          a:List1,
          b:List3
        }
      },
      {
        path:'list3',
        components:{
          default:List3,
          a:List1,
          b:List2
        }
      }
    ]
  }
]

这样会让也面很灵活,可以研究一下

你可能感兴趣的:(33、vue 中 命名视图的用法(二))