[Vuejs]-Vue.js: attempting to fadeOut() one image and fadeIn() another

0👍

setTimeout context

The context is not properly set in setTimeout(function() {});, so this is not your Vue component within the timer callback. If your project allows ES6, you could use an arrow function to fix the issue:

setTimeout(() => {
  this.image = '...';
}, 2000);

On the other hand, if you could only use ES5, you’d have to use Function#bind to fix the issue:

setTimeout(function() {
  this.image = '...';
}.bind(this), 2000);

…or pass in a reference to this:

var self = this;
setTimeout(function() {
  self.image = '...';
}, 2000);

Fading image

You could use Vue’s <transition> to fade the <img>:

new Vue({
  el: '#demo',
  data() {
    return {
      show: true
    }
  }
})
.fade-enter-active, .fade-leave-active {
  transition: opacity .3s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
<script src="https://unpkg.com/vue@2.5.16"></script>

<div id="demo">
  <button v-on:click="show = !show">
    Toggle image
  </button>
  <div>
    <transition name="fade">
      <img v-if="show" src="//placekitten.com/100/100" alt="kitten">
    </transition>
  </div>
</div>
👤tony19

Leave a comment