vue 根据动态样式的宽度设置 img 高度

新手上路,请多包涵

我有一个图像,它的宽度应该有 50% 的高度。

 <img :src="post.image" ref="image" :style="{ height: imageHeight + 'px' }" />

imageHeight() {
            let image = this.$refs.image
            if(!image) return 0
            let height = image.clientWidth * 0.5
            return height
        }

不幸的是,在评估 imageHeight 期间图像未定义,并且当宽度发生变化时它不会重新评估。有没有办法让它与观察者或其他方式一起工作?

原文由 Chris 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
1 个回答

您可以使用 load 事件 来设置变量。看起来您正在使用计算,但没有数据更改可以响应。

 new Vue({
  el: '#app',
  data: {
    url: 'http://via.placeholder.com/200x200',
    imageHeight: null
  },
  methods: {
    setheight(event) {
      let image = event.target;
      this.imageHeight = image.clientWidth * 0.5;
    }
  }
});
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <img :src="url" @load="setheight" :style="{ height: imageHeight + 'px' }">
  <div>{{imageHeight}}</div>
</div>

原文由 Roy J 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题