简体   繁体   English

无法使用 $el 在 Vue js 中获取 clientHeight

[英]Can't get clientHeight in Vue js using $el

I want to get client height of my app using this code :我想使用以下代码获取我的应用程序的客户端高度:

mounted() {
    document.onreadystatechange = () => {
      if (document.readyState == "complete") {
        console.log("Page completed with image and files!");
        console.log(this);
        console.log(this.$el.clientHeight);
      }
    };
}

In console.log(this) I can see my main element and clientHeight of that is 702 , but console.log(this.$el.clientHeight) result is 0 .console.log(this)我可以看到我的主要元素和clientHeight702 ,但console.log(this.$el.clientHeight)结果是0

Also I'm using Framework7 to creating my application UI.此外,我正在使用 Framework7 来创建我的应用程序 UI。

What can I do about this problem?我该怎么办? Any help will greatly appreciate.任何帮助将不胜感激。

Set a ref="potato" on your component template, if that is an valid option for you, and then console.log(this.$refs.potato.clientHeight);在你的组件模板上设置一个ref="potato" ,如果这对你来说是一个有效的选项,然后console.log(this.$refs.potato.clientHeight); will give you the component height.会给你组件高度。

To get a component's height, @Victor Popescu answer is good.要获得组件的高度,@Victor Popescu 的答案很好。

But if client height size is needed, I think this way is better.但是如果需要客户端高度大小,我认为这种方式更好。

 new Vue({ el: '#app', data: { clientHeight: 0 }, created() { window.addEventListener('resize', this.handleResize); this.handleResize(); }, destroyed() { window.removeEventListener('resize', this.handleResize); }, methods: { handleResize() { this.clientHeight = window.innerHeight; } } });
 html, body, #app, section { height: 100%; } h2 { padding: 2rem 0; text-align: center; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <section> <h2 class="title is-2"> Height: {{ clientHeight }} </h2> </section> </div>

You can watch clientHeight also to set any other component's height.您还可以查看 clientHeight 以设置任何其他组件的高度。

watch: {
      clientHeight: function(val) {
          if (document.getElementById("elementId")) {
            document.getElementById("elementId").style.height = val + 'px'
          }
      }
  },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM