Vuejs-根据高度/宽度比将类添加到img [关闭]

问题描述 投票:-2回答:1

我正在将Vuejs用于具有模式图像滑块(通过api调用从数组填充)的网站前端。我希望横向图像的高度小于纵向图像的高度,这是通过运行@load的方法完成的。

   <img id="img"
    :src="image url"
    :ref="'el' + index"
    @load="orientation(index)">

   methods: {
     orientation: function (index) {
       var $container = this.$refs['el' + index]
       if ($container[0].clientHeight < $container[0].clientWidth) {
         $container[0].classList.add('landscape')
       }
     }
   }

这有效,但是图像显示了几秒钟没有添加类的情况,然后添加了类并调整了大小。有没有一种更好的方法可以防止图像尺寸的可见变化。

谢谢

编辑..............................................

我通过img标签上的v-if =“ imageResized”修复了此问题,并将imageResize更改为方法的末尾。

  <template>
   <slider>
     <slider-item class="slider-item" v-for="(galleries, index) in gallery" :key="index">
      <img id="img"
           :if="imageResized"
           :src="galleries.url"
           :ref="'el' + index"
           @load="orientation(index)">
     </slider-item>
    </slider>
   </template>

   <script>
    import { Slider, SliderItem } from 'vue-easy-slider'
    export default {
         name: 'modal',
         components: {
           Slider,
           SliderItem,
           imageResized,
           gallery: [
             { url: 'https://images.freeimages.com/images/large-previews/851/poppies-1369329.jpg' },
             { url: 'https://images.freeimages.com/images/large-previews/9c1/leaf-after-rain-1397121.jpg' }
           ]
         },
         methods: {
           orientation: function (index) {
             var $container = this.$refs['el' + index]
             if ($container[0].clientHeight < $container[0].clientWidth) {
               $container[0].classList.add('landscape')
               this.imageResized = true
             }
           }
         }
  </script>
  <style>
    #img {
      -webkit-box-shadow: 8px 10px 8px rgba(0,0,0,.33);
      box-shadow: 8px 10px 8px rgba(0,0,0,.33);
      object-fit: contain;
      max-height: 98vh;
      max-width: 98vw;
      height: 98%;
      padding-top: 1vh;
    }
    .slider-item {
     max-height: 85%;
     margin-top: 3%;
    }
    .landscape {
      height: 80% !important;
      padding-top: 9vh !important;
     }
   </style>

我认为应该可以使用@depperm。

javascript vue.js image-manipulation
1个回答
0
投票

您可以使用“类对象”来有条件地设置样式。参见here

<img id="img"
    :src="image url"
    :ref="'el' + index"
    v-bind:class="classObject">

<style>
.landscape ...
</style>

computed: {
  classObject: function () {
    return {
      landscape: this.isLandscape(),
    }
  }
},
methods: {
  isLandscape() {
    // answer a bool here
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.