【问题标题】:Vuetify dynamic height for v-imgv-img 的 Vuetify 动态高度
【发布时间】:2020-03-03 08:40:34
【问题描述】:

我有一个容器不是 100% 的页面高度,它是 80% 加上顶部和底部的 60px。 所以里面的图片应该继承容器的高度。

使用 <img /> 和一点 CSS 很容易实现,但我希望添加一个带有加载微调器的模板,因此我开始使用 <v-img>

我可以看到我可以设置heightmax-height,所以我做了一个方法来计算父高度减去 120px 以获得确切的图像高度,它按预期工作。

问题是当用户调整窗口大小时,我可以看到要调用的方法并更新值,但 vuetify 元素对新值没有响应,因此图像大于或小于容器:

<div id="photoWrapper" class="photo-wrapper">
  <v-img
    :src="photo.url"
    :contain="true"
    :max-height="wrapperHeight()"
  >
    <template v-slot:placeholder>
      <v-layout fill-height align-center justify-center ma-0>
        <v-progress-circular
          indeterminate
          color="tertiary"
        ></v-progress-circular>
      </v-layout>
    </template>
  </v-img>
</div>

代码:

data() {
  return {
    mounted: false
  }
},
mounted() {
  this.mounted = true
  window.addEventListener('resize', this.wrapperHeight)
  this.wrapperHeight()
},
methods: {
  wrapperHeight() {
    if (!this.mounted) return
    console.log(document.getElementById('photoWrapper').offsetHeight - 120)
    const height = document.getElementById('photoWrapper').offsetHeight - 120
    return height
  }
}

该方法总是在屏幕调整大小时调用,但图像没有响应。 我该怎么做?我还尝试将wrapperHeight 移动为计算属性。

【问题讨论】:

  • 您在挂载中调用 wrapperHeight(返回值未使用),并且还尝试绑定到属性。如果你想绑定,你应该使用计算属性。这在这里行不通,因为 vue 不知道何时触发它,因为 document.** 函数不是反应式的。您可以将包装器高度的结果分配给数据成员并使用它。
  • 请用更多细节丰富这个pen,让我们调试它

标签: javascript vue.js vuetify.js


【解决方案1】:

你需要让你的 wrapperHeight 是一个计算属性。这是正确的,并且比创建类似方法的性能更好。

computed: {
      wrapperHeight() {
          if (!this.mounted) return
          console.log(document.getElementById('photoWrapper').offsetHeight - 120)
          const height = document.getElementById('photoWrapper').offsetHeight - 120
          return height
      }
  }

并且 :max-height="wrapperHeight" 不是 :max-height="wrapperHeight()"

【讨论】:

  • 这是我的第一次尝试,我在我的问题结束时说...不幸的是它不起作用。它在开始时获取第一个值,然后在调整大小时不再触发计算属性...
【解决方案2】:

解决方案是在计算方法和方法之间进行混合,如下所示:

data() {
  return {
    mounted: false,
    containerHeight:
      document.getElementById('photoWrapper').offsetHeight - 120
  }
},
computed: {
  wrapperHeight() {
    if (!this.mounted) return
    const height = this.containerHeight
    return height
  }
},
mounted() {
  this.mounted = true
  window.addEventListener('resize', _.debounce(this.handleResize, 100))
},
beforeDestroy() {
  window.removeEventListener('resize', this.handleResize)
},
methods: {
  handleResize() {
    this.containerHeight =
      document.getElementById('photoWrapper').offsetHeight - 120
  }
}

【讨论】:

    【解决方案3】:

    我认为你必须在wrapperHeight 方法中返回${height}px

    【讨论】:

    • 很遗憾没有,vuetify 接受number | string
    • 你好弗拉德,请检查你的答案格式,你的反引号被 stackoverflow 降价引擎吃掉了。
    • 试着把它变成一个getter,而不是一个方法?
    • 这什么也没做,因为 Vuetify 接受 100 或 "100px"。
    猜你喜欢
    • 2019-07-31
    • 2019-11-10
    • 2020-10-29
    • 2021-02-09
    • 2020-05-09
    • 2021-05-16
    • 2020-11-05
    • 2022-06-18
    • 1970-01-01
    相关资源
    最近更新 更多