vue div自适应高度

第一种:利用弹性盒子flex特性
vue div自适应高度_第1张图片


<template>
  <div class='container'>
    <div class="divContent">
      <div class="div1">1高度可固定也可不</div>
      <div class="div2">2基于父元素固定高度本身的高度自适应</div>
      <div class="div3">3高度可固定也可不</div>
    </div>

  </div>
</template>

<script lang='ts'>
import Vue from 'vue'
export default Vue.extend({
  data () {
    return {
    }
  },
  methods: {
  }
})
</script>

<style scoped lang='scss'>
  .container{
    height: 100vh;
    width: 100%;
    .divContent{
      height: 50%;
      width: 40%;
      border: 1px solid #f0f0f0;
      display:flex;
      flex-direction: column;
    }
    .div2{
      flex:1;
    }
    .div1,.div3{
      // height: 300px;
      background-color: #f0f0f0;
    }
  }
</style>

第二种:监听其他元素高度
vue div自适应高度_第2张图片

npm install element-resize-detector --save

完整代码为:

<template>
  <div class='container'>
    <div class="divContent">
      <div :style="[{height:divHei+'px'}]" class="div2">在父元素高度固定的情况下根据元素2高度自适应</div>
      <div id="content2" :class="flag?'div3':'div1'">元素2 <i @click="flag=!flag" style="cursor:pointer" class="el-icon-download"></i></div>
    </div>

  </div>
</template>

<script lang='ts'>
import Vue from 'vue'
import elementResizeDetectorMaker from 'element-resize-detector'
export default Vue.extend({
  data () {
    return {
      divHei: 0,
      flag: false
    }
  },
  mounted () {
    const self = this
    const erd = elementResizeDetectorMaker()
    erd.listenTo(document.getElementById('content2'), element => {
      self.$nextTick(() => {
        this.divHei = 300 - element.clientHeight
      })
    })
  },
  methods: {
  }
})
</script>

<style scoped lang='scss'>
  .container{
    height: 100vh;
    width: 100%;
    .divContent{
      height: 300px;
      width: 40%;
      border: 1px solid red;
      background-color: antiquewhite;
    }
    .div1{
      height: 30px;
      background-color: #f0f0f0;
    }
    .div3{
      height: 100px;
      background-color: #f0f0f0;
    }
  }
</style>

你可能感兴趣的:(前端问题汇总,vue.js,javascript,前端)