Vue2.0 image load event
by Chris Ball
HTML
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/css-spinning-spinners/1.1.1/load5.css">
<div id="app">
<button @click="loadImg">load image</button>
<ul>
<li>{{url}}</li>
<li>{{index}}</li>
<li>{{images[index]}}</li>
<li>{{isLoad}}</li>
</ul>
<div class="img-box">
<transition>
<img v-show="isLoad" :src="url" @load="loaded">
</transition>
<div v-show="!isLoad" class="loading">Loading...</div>
</div>
</div>
SCSS
#app {
padding: 20px;
width: 500px;
border: 3px solid #ccc;
background-color: #fff;
img {
width: 100%;
height: auto;
}
}
.img-box{
position: relative;
min-height: 100px;
img {
transition: all .3s ease;
height: 30px;
padding: 10px;
margin: 0;
background-color: #eee;
overflow: hidden;
}
img.v-enter, img.v-leave {
height: 0;
padding: 0 10px;
opacity: 0;
}
}
.loading {
text-indent: -9999px;
}
JavaScript
var app = new Vue({
el: '#app',
data: {
url: "",
index: 0,
images: [
'https://68.media.tumblr.com/ba9e2dcf1289131bfae913ff85cc8e46/tumblr_omrhdiHNlD1u8in0ho1_1280.jpg',
'https://jp.vuejs.org/images/logo.png',
'https://jsfiddle.net/img/[email protected]'
],
isLoad: false
},
created() {
this.loadImg()
},
methods: {
loadImg() {
this.isLoad = false
this.$nextTick(() => {
this.url = this.images[this.index];
this.index = (this.index < this.images.length - 1) ? this.index + 1 : 0
})
},
loaded() {
this.isLoad = true
}
}
})