【问题标题】:How to access vm.$el properties with single-file components?如何使用单文件组件访问 vm.$el 属性?
【发布时间】:2017-03-20 05:24:59
【问题描述】:

我正在尝试访问由单文件组件创建的 vue 实例的 clientHeightproperty,但它返回未定义。我该怎么做?

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

【问题讨论】:

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


    【解决方案1】:

    您可以使用this.$el 访问mounted 之后的元素,因此您实际上需要在安装后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,
        }
      }
    }
    

    【讨论】:

    • 这对我不起作用。即使在mounted() 函数中,this 仍然是undefined。这似乎是单个文件组件的问题。
    • this 未定义真的很奇怪。你确定不是this.$el 是未定义的吗?如果是这样,您可能在不应该使用的地方使用了箭头函数。
    • 你是绝对正确的@bill-criswell 我有module: () =&gt; {} 而不是module() {},这一切都不同了。谢谢!
    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 2014-06-01
    • 2017-07-26
    • 2018-01-06
    相关资源
    最近更新 更多