Vue-三栏布局组件

958 阅读1分钟

写一个vue的组件—————蕴含插槽的三栏布局,在网页的布局中很重要,且具有灵活性

  1. 组件整体是一个三栏布局
  2. 每栏使用了具名插槽。组件的高撑满父元素,宽度自适应,根据子元素来。如果对应的具名插槽中不填充东西,对应的一栏就会自然不显现

flex三栏布局

样式介绍

  1. flex布局方向这里设置为默认,即水平方向
  2. 左右栏不可压缩,不可拉伸

buju.vue中的内容如下

<template>
  <div class="buju-container">
      <div class="left"><slot name="left"></slot></div>
      <div class="main"><slot></slot></div>
      <div class="right"><slot name="right"></slot></div>
  </div>
</template>

<script>
export default {
    name: 'buju',
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}
.buju-container{
    width: 100%;
    height: 100%; 
    display:flex;
}
.left{
    flex:0 0 auto;
    height: 100%;
}
.right{
    flex:0 0 auto;
    height: 100%;
}
.main{
    flex:1 1 auto;
    height: 100%;
    overflow: hidden;
}
</style>

父组件中使用该组件

由于组件中buju-container高度设为100%,因此组件的真实高度,取决于父容器的真实高度

测试组件中,父容器id="app"的div高度设置为100vh

具名插槽使用v-slot:left或v-slot:right指定插入位置

<template>
  <div id="app">
    <buju class="buju-container">
      <template v-slot:left
        ><div style="background-color: red">left</div></template
      >
      <template><div style="background-color: green">middle</div></template>
      <template v-slot:right
        ><div style="background-color: blue">right</div></template
      >
    </buju>
  </div>
</template>

<script>
import buju from "./";
export default {
  components: {
    buju,
  },
};
</script>

<style scoped>
#app {
  height: 100vh;
  background-color: yellowgreen;
}
div{
  height: 100%;
  font-size: 30px;
  color: white;
}
.buju-container {
  height: 100%;
  background-color: #333;
}
</style>

4BXV)MPZNWAERHI$L3(~32C.png

如果注释掉插入right的部分

<template>
  <div id="app">
    <buju class="buju-container">
      <template v-slot:left
        ><div style="background-color: red">left</div></template
      >
      <template><div style="background-color: green">middle</div></template>
      <!-- <template v-slot:right
        ><div style="background-color: blue">right</div></template
      > -->
    </buju>
  </div>
</template>

效果图 布局3.png