suzy1997
suzy1997

Reputation: 13

use vanilla-lazyload with vuejs

I'm pretty new in Vue-js and I'm trying to use this.

My App is not a SPA and I'm also working with Laravel.

I've tried this and it works fine:

const app = new Vue({
    el: '#app',
    mounted() {
        this.myLazyLoad = new LazyLoad({
            elements_selector: '.lazy',
            class_loaded: 'lazy-loaded',
            load_delay: 500, //adjust according to use case
            threshold: 100, //adjust according to use case,
            callback_enter: function(el) {
                console.log(el.getAttribute("data-src"));
            }
        }); 
    }
});

 <img data-src="{{ $featuredItem->anime->getPortraitImg()}}" 
    class="lazy img-fluid" src="/img/placeholder-anime.jpg">

But there is a problem when I try to use the lazyload in a Component. For example:

export default {
  mounted() {
        console.log('Component mounted.');
        console.log(Vue.prototype.LazyLoad);

        this.myLazyLoad = new LazyLoad({
            // elements_selector: '.lazyx',
            container: document.getElementById('lazyContainer')                
        });

        // myLazyLoad.loadAll();
    },
    data() {
        return {
            episodes: {},
            currentPage: 2      
        }  
    },
    methods: {
        loadMoreEpisodes() {
            let uri = '/api/v1/episodes?page=' + this.currentPage;

            this.axios.get(uri).then(response => {
                console.log(response.data.data);

                if (this.episodes.length === undefined) {
                    this.episodes = response.data.data;
                } else {
                    this.episodes = this.episodes.concat(response.data.data);
                }

                this.myLazyLoad.update();
                this.myLazyLoad.loadAll();
            });
        }
    }
}

The new data inserted by axios is not recognized by the lazyload plugin.

I'm using this.myLazyLoad.update(); as stated in the documentation, but I'm not able to get it to work. Any suggestions?

Upvotes: 1

Views: 534

Answers (1)

ittus
ittus

Reputation: 22403

I think DOM is not updated when you call update() method. Can you try using $nextTick?

this.$nextTick(() => {
  this.myLazyLoad.update()
})

Upvotes: 1

Related Questions