无法使用 $el 在 Vue js 中获取 clientHeight
Can't get clientHeight in Vue js using $el
我想使用此代码获取我的应用程序的客户端高度:
mounted() {
document.onreadystatechange = () => {
if (document.readyState == "complete") {
console.log("Page completed with image and files!");
console.log(this);
console.log(this.$el.clientHeight);
}
};
}
在 console.log(this)
中我可以看到我的主要元素,其中 clientHeight
是 702,但 console.log(this.$el.clientHeight)
结果是 0.
此外,我正在使用 Framework7 创建我的应用程序 UI。
这个问题我该怎么办?
任何帮助将不胜感激。
在你的组件模板上设置一个 ref="potato"
,如果这对你来说是一个有效的选项,然后 console.log(this.$refs.potato.clientHeight);
会给你组件高度。
要获取组件的高度,@Victor Popescu 的回答很好。
但是如果需要客户端高度尺寸,我觉得这种方式更好。
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>
您也可以通过观察 clientHeight 来设置任何其他组件的高度。
watch: {
clientHeight: function(val) {
if (document.getElementById("elementId")) {
document.getElementById("elementId").style.height = val + 'px'
}
}
},
我想使用此代码获取我的应用程序的客户端高度:
mounted() {
document.onreadystatechange = () => {
if (document.readyState == "complete") {
console.log("Page completed with image and files!");
console.log(this);
console.log(this.$el.clientHeight);
}
};
}
在 console.log(this)
中我可以看到我的主要元素,其中 clientHeight
是 702,但 console.log(this.$el.clientHeight)
结果是 0.
此外,我正在使用 Framework7 创建我的应用程序 UI。
这个问题我该怎么办? 任何帮助将不胜感激。
在你的组件模板上设置一个 ref="potato"
,如果这对你来说是一个有效的选项,然后 console.log(this.$refs.potato.clientHeight);
会给你组件高度。
要获取组件的高度,@Victor Popescu 的回答很好。
但是如果需要客户端高度尺寸,我觉得这种方式更好。
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>
您也可以通过观察 clientHeight 来设置任何其他组件的高度。
watch: {
clientHeight: function(val) {
if (document.getElementById("elementId")) {
document.getElementById("elementId").style.height = val + 'px'
}
}
},