vue 获取元素宽高

vue 中获取组件宽高分两种情况:
1、获取普通组件宽高,直接使用 $refs 即可
2、获取子组件宽高,需使用 $refs.$el

子组件

<template>
  <div class="div_box">这是一个子组件</div>
</template>

<script>
export default {
  name: 'ChileHeight'
}
</script>

<style lang="scss" scoped>
.div_box {
  padding: 20px;
  border: 20px solid red;
}
</style>

父组件

<template>
  <div class="home">
    <div class="div_card" ref="attrRef">获取元素高度</div>
    <child-height ref="childRef"></child-height>
  </div>
</template>

<script>
import ChildHeight from './note/child-height.vue'
export default {
  name: 'Home',
  components: {
    ChildHeight
  },
  mounted() {
    // 获取元素宽高
    const w = this.$refs.attrRef.offsetWidth
    const h = this.$refs.attrRef.offsetHeight
    console.log('获取元素宽高', w, h)
    // 获取子组件元素宽高
    const w_child = this.$refs.childRef.$el.offsetWidth
    const h_child = this.$refs.childRef.$el.offsetHeight
    console.log('获取子组件元素宽高', w_child, h_child)
  }
}
</script>
<style scoped>
.div_card {
  padding: 20px;
  border: 10px solid yellow;
}
</style>

ref


clientHeightoffsetHeight 区别

clientHeight:包括padding但不包括border、水平滚动条、margin的元素的高度
offsetHeight:包括padding、border、水平滚动条,但不包括margin的元素的高度

height

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐