Created
December 5, 2018 18:17
-
-
Save icodesido/b09ca90bbbd54b96e4a950cda0f6c106 to your computer and use it in GitHub Desktop.
Lazy loading in Vue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <div id="app"> | |
| <h1>Lazy-Loading Image:<br /> Easily Editable Aspect Ratio<br /> In Vue</h1> | |
| <lazy-load data-src="https://images.unsplash.com/photo-1524654458049-e36be0721fa2?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=1a6782be5cdb94b780ed9d4a79de7041" width="600" height="400" alt="sample image" /> | |
| </div> | |
| Vue.component('lazy-load', { | |
| data: function() { | |
| return { | |
| unloaded: true, | |
| src: this.placeholderSrc(this.width, this.height) | |
| } | |
| }, | |
| props: ['dataSrc', 'height', 'width', 'alt'], | |
| methods: { | |
| loadImage: function() { | |
| this.unloaded = false | |
| this.src = this.dataSrc | |
| }, | |
| placeholderSrc(w, h) { | |
| return `data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}"%3E%3C/svg%3E` | |
| } | |
| }, | |
| template: `<div><img :src="src" :alt="alt" /><button v-if="unloaded" @click="loadImage">Click to Load</button></div>` | |
| }) | |
| const v = new Vue({el: '#app'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment