1. 程式人生 > >vue路由—實現經典佈局(同一個路由,對應多個元件)

vue路由—實現經典佈局(同一個路由,對應多個元件)

要點:

1.router-view頭部,側邊欄,主體內容區域三個區域,每個有一個佔位符。

2.佔位符定義一個name屬性,跟components的第一個屬性對應,這裡component使用複數,同一個路由下匹配多個元件。

HTML程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../lib/vue.js"></script>
    <script src="../lib/vue-router.js"></script>
    
    <style>
        .header{
            margin-top: 25px;
            background-color: gray;
            height: 125px;
        }
        .container{
            display:flex;
            /*flex左右佈局,一共十份,bootstrap的柵格12份*/
            height: 575px;
        }
        .left{
            background-color: gainsboro;
            flex: 2.5;
        }
        .main{
            background-color: honeydew;
            flex: 7.5;
        }
        
        h1{
            padding: 0px;
            margin: 0px;
        }
    </style>
</head>
<body>
      <div id="app">
          
          <router-view></router-view>
          
          <div class="container">
              <router-view name="left"></router-view>
              <router-view name="main"></router-view>
          </div>
          <!--頭部,側邊欄,主體內容區域三個區域,每個有一個佔位符-->
          <!--name是為了將components中的多個元件一一對應起來-->
          
      </div>

      <script>
          
          var header = {
              template: '<h1 class="header">head頭部區域</h1>'
          };
          
          var leftNav = {
              template: '<h1 class="left">left側邊欄</h1>'  
          };
          
          var mainContent = {
              template: '<h1 class="main">main主體內容</h1>'
          };
          
          var router = new VueRouter({
             routes:[
                 {path:'/', components:{
                     default:header,
                     'left':leftNav,
                     'main':mainContent
                 }}
                 //這裡使用複數components,第一個屬性與router-view中的name對應,第二個是表示要展示的元件名字    
             ] 
          });
          
          
          
          var vm = new Vue({
             el:'#app',
             router
          });
      </script>
</body>
</html>

效果: