$refs 取得元件高度 - daniel-qa/Vue GitHub Wiki
$refs 取得元件高度
DOM 元素引用 (ref
)
-
在模板中使用
ref="xxx"
標記元素。 -
在 JavaScript 中使用
this.$refs.xxx
存取該元素。 -
常見用法:
this.$refs.container.offsetHeight
(取得高度)、this.$refs.input.focus()
(設定焦點)。 -
注意:
$refs
只有在元件掛載後(如mounted()
生命週期鉤子)才能存取。 ... -
ex
<template>
<div>
<div ref="myElement">
這是我的主要區塊。
</div>
<p>區塊高度:{{ myHeight }} px</p>
</div>
</template>
<script>
export default {
data() {
return {
myHeight: 0
};
},
mounted() {
// 3. 在 mounted 後取得高度
this.myHeight = this.$refs.myElement.offsetHeight;
}
};
</script>