我试图访问由单个文件组件创建的vue实例的clientHeight
属性,但它返回undefined。我怎么能这样做?
<template lang='jade'>
article#article.projectCard.relative.mb5.pa5( v-bind:style="styleObject")
h3 {{ project.projectName }}
p {{ project.projectDescription }}
</template>
<script>
export default {
props: {
project: '',
},
data () {
return {
styleObject: {
backgroundColor: this.project.projectMainColor,
height: '80vh'
},
cardHeight: this.clientHeight,
};
},
</script>
答案 0 :(得分:2)
您可以使用mounted
this.$el
之后访问该元素,因此在安装后您实际需要this.$el.clientHeight
。
你可以这样做:
data () {
return {
cardHeight: 0,
}
}
然后做:
mounted () {
this.cardHeight = this.$el.clientHeight + 'px'
}
此外,styleObject
作为计算属性会更好。这样一来,随着事情的变化,它会自动更新。
我个人会这样做:
data () {
return {
cardHeight: '80vh',
}
},
mounted () {
this.cardHeight = this.$el.clientHeight + 'px'
},
computed: {
styleObject () {
return {
backgroundColor: this.project.projectMainColor,
height: this.cardHeight,
}
}
}