How to fade in images when loaded with Vue

ksl*_*stn 5 javascript vuejs2

I created this component that fades in an image once it is loaded to the client. I would think there is a more Vue-like way to solve this, like using Vue events, but could not find it. What is the Vue way to detect when an image is loaded?

https://codepen.io/kslstn/pen/ooaPGW

Vue.component('imageThatFadesInOnLoad',{

  data: function(){
    return {
      src: 'http://via.placeholder.com/350x150',
      loaded: false,
    }
  },

  mounted: function () {
    var image = new Image()
    var that =  this
    this.loaded = image.addEventListener('load', function(){that.onLoaded()}) // This is the key part: it is basically vanilla JS
    image.src = this.src
  },

  methods:{
    onLoaded(){
      this.loaded = true
    }
  },

  template: `
    <div class="wrapper">
      <transition name="fade">
        <img class="icon" v-bind:src="src" v-if="loaded">&nbsp;
      </transition>
   </div>
  `
})

new Vue({
  el: '#wrapper'
});
Run Code Online (Sandbox Code Playgroud)
.wrapper{
  width: 350px;
  height: 150px;
  background: slategrey;
}
.fade-enter-active {
  transition: opacity 3s ease-in-out;
}
.fade-enter-to{
  opacity: 1;
}
.fade-enter{
  opacity: 0;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.4.4/dist/vue.js"></script>
<div id="wrapper">
<image-that-fades-in-on-load></image-that-fades-in-on-load>
</div>
Run Code Online (Sandbox Code Playgroud)

yur*_*636 9

您可以使用v-on:(或@简写)语法来绑定到任何DOM事件。就您而言,load事件是在加载图像时触发的。

由于您正在以“ DOM方式”加载图像,因此无法使用,v-if因为Vue不会渲染该元素(但您需要这样做,因此将提取图像src)。相反,您可以使用v-show,它将呈现但隐藏元素。

Vue.component('imageThatFadesInOnLoad', {
  data: function() {
    return {
      src: 'http://via.placeholder.com/350x150',
      loaded: false,
    }
  },
  methods: {
    onLoaded() {
      this.loaded = true;
    }
  },
  template: `
    <div class="wrapper">
      <transition name="fade">
        <img class="icon" v-bind:src="src" v-on:load="onLoaded" v-show="loaded">&nbsp;
      </transition>
   </div>
  `
});

new Vue({
  el: '#wrapper'
});
Run Code Online (Sandbox Code Playgroud)
.wrapper {
  width: 350px;
  height: 150px;
  background: slategrey;
}

.fade-enter-active {
  transition: opacity 3s ease-in-out;
}

.fade-enter-to {
  opacity: 1;
}

.fade-enter {
  opacity: 0;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.4.4/dist/vue.js"></script>

<div id="wrapper">
  <image-that-fades-in-on-load></image-that-fades-in-on-load>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 我认为这仅适用于第一次加载。至少在我的情况下。因为如果图像已经缓存,则不会触发@load 事件。如果没有@load 事件,`this.loaded` 将永远不会被设置为真正隐藏我的图像...... - 不过到目前为止我还没有找到合适的解决方案。– 但我也看到你的 codepen 正在工作...... 我的代码没有 ‍♂️ (2认同)