温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在vue项目中命名视图

发布时间:2021-01-12 15:02:56 来源:亿速云 阅读:223 作者:Leah 栏目:web开发

今天就跟大家聊聊有关如何在vue项目中命名视图,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

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

例如:

{
  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。

<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>

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

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

解释一下:

在这个默认路由下,

第一个非未命名视图显示Foo组件

第二个name名为a的视图显示Bar组件

第二个name名为b的视图显示Baz组件

然后自己有些了个demo

<template>
  <div class="hello">
    <ul class="nav">
      <li><router-link to="/list1">list1</router-link></li>
      <li><router-link to="/list2">list2</router-link></li>
      <li><router-link to="/list3">list3</router-link></li>
    </ul>
    <h7>默认视图</h7>
    <div class="view">
      <router-view></router-view>
    </div>
    <h7>a视图</h7>
    <div class="view">
      <router-view name="a"></router-view>
    </div>
    <h7>b视图</h7>
    <div class="view">
      <router-view name="b"></router-view>
    </div>
  </div>
</template>

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
        }
      }
    ]
  }
]

看完上述内容,你们对如何在vue项目中命名视图有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI