如何使用单文件组件访问vm。$ el属性?

时间:2016-11-06 22:57:09

标签: node.js vue.js vue-component webpack-2

我试图访问由单个文件组件创建的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>

1 个答案:

答案 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,
    }
  }
}