Vue.js: попытка fadeOut () одного изображения и fadeIn () другого - PullRequest
0 голосов
/ 09 июня 2018

Этот рабочий бит кода (при условии, что на сервер загружен файл foo / foo_ad1.jpg thru foo / foo_ad11.jpg) загружает случайное изображение из банка изображений и заменяет его другим изображением каждые несколько секунд.

Я пытаюсь сделать так, чтобы картинки плавно исчезали, и вот тут я сталкиваюсь с двумя проблемами:

1) Я не могу отобразить «this.image», когда япереместите его в функцию setTimeOut.

2) Я не смог заставить работать fadeIn () или fadeOut (), я даже не уверен, какой будет правильный синтаксис.

Пожалуйста, смотрите комментарии, добавленные в коде.TY

JS:

Vue.component('foo-ad-module', {
    data() {
        return {
            image:  'foo/foo_ad1.jpg',
            timer:  '',
            x:          0
        }
    },
    created: function() {
        this.replaceImage();
        this.timer = setInterval(this.replaceImage, parseInt((Math.random() * 33599)%30000) + 5000)
    },  
    methods: {
        init(){
            this.x = parseInt((Math.random() * 33599)%11) + 1;
              this.image = 'foo/foo_ad' + this.x + '.jpg';
              console.info("this.image = " + this.image);
       },
       replaceImage: function() {
            this.x = parseInt((Math.random() * 33599)%11) + 1;
//#if
           this.image = 'foo/foo_ad' + this.x + '.jpg';     // ...THIS WORKS (when it is outside the setTimeout())
//#else
//          $(???).fadeOut("2000");                                     // ... intending to put a fadeOut() here...
            setTimeout(function () {        
                console.info("this is working...");                                                          
//              this.image = 'foo/foo_ad' + this.x + '.jpg';    // ... THIS DOESN'T WORK (when it is inside the setTimeout())
//              $(???).fadeIn("2000");                                  //  ... intending to put a fadeIn() here...                                         
            }, 2000);
//#endif            

            clearInterval(this.timer)         
        this.timer = setInterval(this.replaceImage, (parseInt((Math.random() * 33599)%30000) + 5000));        
       },
  },
    beforeDestroy() {
      clearInterval(this.timer)
    },  
    mounted(){
        this.init()
    },  
    template: `
                <div class="foo-ad-module " >
               <img :src="image" alt="hi there">
                </div>  `
});

CSS:

.foo-ad-module {
    width:          198px;
    height:         198px;
    border:         1px solid #555;     
    border-radius:  10px;
    margin-bottom:  10px;
}

1 Ответ

0 голосов
/ 10 июня 2018

setTimeout context

Контекст неправильно установлен в setTimeout(function() {});, поэтому this не является вашим компонентом Vue в обратном вызове таймера.Если ваш проект поддерживает ES6, вы можете использовать функцию стрелки для решения проблемы:

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

С другой стороны, если вы можете использовать только ES5, вам придется использоватьFunction#bind для устранения проблемы:

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

... или передайте ссылку на this:

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

Исчезающее изображение

Вы можете использовать Vue <transition>, чтобы исчезнуть <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>
...