如何访问vm.$el属性与单文件组件



我试图访问由单文件组件创建的值实例的clientHeight属性,但它返回未定义。我该怎么做呢?

<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>

您可以在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,
    }
  }
}

最新更新