vue.js动态设置VueComponent高度问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue.js动态设置VueComponent高度问题

condragte   2022-09-28 我要评论

vue.js动态设置VueComponent高度的问题

1.获取HTML元素高度

<div v-for="data in list">
    <div ref="abc">{{data.id}}</div>
</div>
mounted(){
    console.log(this.$refs.abc[0].clientHeight);//获取第一个div元素的高度
    this.$refs.abc[0].style.height = 100 +'px';//动态设置HTML元素高度
}

注意:

  • 1.此处用到v-for循环,this.$refs.abc返回的是个HTMLElement数组
  • 2.this.$refs在DOM元素挂载完成后才可以调用
  • 3.不可以通过this.$refs.abc[0].clientHeight = 100 +'px'设置高度,因为clientHeight属性是只读的,不允许修改。
  • 4.注意加'px'单位

2.获取VueComponent标签生成的元素的高度

<Row v-for="(data,idx) in list" :key="idx">
   <Col ref="leftCol">
      <p>{{data.id}}</p>
   </Col>
   <Col ref="rightCol">
      <p>{{data.id}}</p>
   </Col>
</Row>
mounted(){
    for(let i = 0; i < this.list.length; i++){
      console.log(this.$refs.leftCol[i].$el.clientHeight);//获取左边列元素的高度
      console.log(this.$refs.rightCol[i].$el.clientHeight);//获取右边列元素的高度
      this.$refs.leftCol[0].$el.style.height = 100 +'px';//动态设置VueComponent元素高度    
    };
}

注意:

this.$refs.leftCol返回的是个VueComponent数组,this.$refs.leftCol[i]返回的是个VueComponent元素,而不是HTMLElement

3.判断一个对象是jQuery对象还是DOM对象

var jqueryObject = $("#a");
jqueryObject instanceof jQuery; //jqueryObject 是jQuery对象
var domObject = document.querySelector("#a");
domObject instanceof jQuery; //domObject不是jQuery对象
domObject instanceof HTMLElement; //domObject是DOM对象

vue动态获取、设置组件高度

<template>
  <el-row>
    <el-col :span="24">
      <el-row ref="headerMenu" class="header-menu">
        <el-col :span="24">
          <el-menu router mode="horizontal">
            <el-menu-item index="1" route="/global-overview">全局概览</el-menu-item>
            <el-menu-item index="2" route="/e-commerce-business">电商业务</el-menu-item>
            <el-menu-item index="3" route="/douniao-business">抖鸟业务</el-menu-item>
            <el-menu-item index="4" route="/administrative-business">行政业务</el-menu-item>
            <el-menu-item index="5" route="/admin">管理员入口</el-menu-item>
          </el-menu>
        </el-col>
      </el-row>
      <el-row ref="routerView">
        <router-view></router-view>
      </el-row>
    </el-col>
  </el-row>
</template>
<script>
export default {
  name: "home-page",
  mounted() {
    /**
     * when the component is hung, dynamically obtain the height of the header menu,
     * and set this value to router view as margin top
     */
    this.$refs.routerView.$el["style"].marginTop = `${this.$refs.headerMenu.$el["offsetHeight"]}px`;
  }
}
</script>
<style scoped>
.header-menu {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 999;
}
</style>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们