vue利用计算属性动态控制div大小

因为需要动态控制div的显示数目,所以需要div的大小能动态变化,这里使用的计算属性来实现

<div class="video" :style="{width: videoWidth + 'px', height: videoHeight + 'px'}"></div>

这里的videoWidth和videoHeight就是计算属性

computed: {
  videoWidth: {
    get: function () {
      // elmWidth是当前控件的宽度
      return this.elmWidth / this.columnNum - 10
    }
  },

  videoHeight: {
    get: function () {
      // elmHeight是当前控件的高度
      return this.elmHeight / this.rowNum - 10
    }
  },

  // rowNum和comunmNum根据当前需要展示的视频数目videoNumShow计算
  // videoNumShow是父组件传递的一个属性
  // 4 -- 2 * 2
  // 9 -- 3 * 3
  // 12 -- 3 * 4
  // 24 -- 4 * 6
  rowNum: {
    get: function () {
      if (this.videoNumShow === 4) return 2
      else if (this.videoNumShow === 9) return 3
      else if (this.videoNumShow === 12) return 3
      else if (this.videoNumShow === 24) return 4
      return 2
    }
  },

  columnNum: {
    get: function () {
      if (this.videoNumShow === 4) return 2
      else if (this.videoNumShow === 9) return 3
      else if (this.videoNumShow === 12) return 4
      else if (this.videoNumShow === 24) return 6
      return 2
    }
  }
}

这样在父组件传递进来的videoNumShow改变时,就会自动改变窗口的大小

另外需要说明的几点

1、elmWidth和elmHeight可以通过ResizeObserver监听动态的获取

mounted () {
  const that = this
  const resizeObserver = new ResizeObserver(entries => {
    for (let entry of entries) {
      console.log(entry)
      that.elmWidth = that.$el.getClientRects()[0].width
      that.elmHeight = that.$el.getClientRects()[0].height
    }
  })

  this.resizeObserver = resizeObserver
  if (this.$el instanceof Element) {
    resizeObserver.observe(this.$el)
  }
  else {
    // 定时检测是否this.$el有效
    setInterval(function () {
      if (that.$el instanceof Element) {
        that.resizeObserver.observe(that.$el)
      }
    }, 1000)
  }

  that.elmWidth = that.$el.getClientRects()[0].width
  that.elmHeight = that.$el.getClientRects()[0].height
}

2、视频的显示数目可以通过绑定class实现

      像下面这个div,在videoNumShow小于5的时候就会隐藏,hide是一个用来隐藏的样式 display: none;

<div class="video" :style="{width: videoWidth + 'px', height: videoHeight + 'px'}" :class="{hide: (videoNumShow < 5)}"></div>

 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值