首页 > 解决方案 > 为什么我的 vue 组件的宽度报告“未定义”?

问题描述

我正在尝试访问 vue 组件的宽度,以便可以动态缩放它所持有的内容。不幸的是,vue 将“宽度”报告为“未定义”,这使我的计划有些悬而未决。

我正在通过 this.$refs 访问有问题的控件。

我在 nextTick() 函数中查询宽度。

如何访问此组件的宽度?

 <v-card class="d-flex flex-row ma-6" color="grey" flat tile outlined min-height="30" ref="tlbox">
    <v-card class="d-flex flex-row" v-for="file in this.layer.timeline" :key=file.index >
      <v-tooltip top>
        <template v-slot:activator="{on,attrs}">
          <v-card class="" color="black" :width=getOffsetWidth(file) >
          </v-card>
          <v-card class="" color="red" width="1" >
          </v-card>
          <v-card v-bind="attrs" v-on="on" class="pa-2" color="grey darken-2" outlined tile :width=getWidth(file) >
          </v-card>
        </template>
        <span>{{ file.src_clip_name }}</span>
      </v-tooltip>
    </v-card>

调整大小处理程序

    handleResize() {
      window.console.log('mth:handleResize')
      window.console.log(this.$store.state.link.duration)
      this.$nextTick(() => {
        this.tlwidth = this.$refs['tlbox'].clientWidth
        window.console.log(this.$refs['tlbox'])
        window.console.log(this.tlwidth)
        if (this.$store.state.link.duration > 0) {
          this.scalefactor = this.tlwidth / this.$store.state.link.duration
        }
      })
    },

这是记录的参考... v-component 日志提取

这是有问题的组件(长灰色的,肯定有宽度)

在此处输入图像描述

标签: javascripthtmlcssvue.jsvuejs2

解决方案


组件是逻辑实体,而不是 DOM 元素;它们没有宽度。与标准标签不同,当一个 ref 被放置在一个组件标签上时,它访问的是它的 Vue 引用,而不是一个 DOM 元素。此外,width您截屏的属性无论如何都不是您要记录的,它是clientWidth正确的。

使用$el组件的属性访问其 DOM 根:

console.log(this.$refs['tlbox'].$el.clientWidth);

推荐阅读