2

我正在尝试访问clientHeight由单文件组件创建的 vue 实例的属性,但它返回未定义。我怎样才能做到这一点?

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

1 回答 1

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,
    }
  }
}
于 2016-11-07T02:01:21.383 回答