我创建了这个组件,它在图像加载到客户端后淡入淡出。我认为有一种更像 Vue 的方法来解决这个问题,比如使用 Vue 事件,但找不到它。 Vue 检测图像何时加载的方法是什么?
https://codepen.io/kslstn/pen/ooaPGW
Vue.component('imageThatFadesInOnLoad',{
data: function(){
return {
src: 'http://via.placeholder.com/350x150',
loaded: false,
}
},
mounted: function () {
var image = new Image()
var that = this
this.loaded = image.addEventListener('load', function(){that.onLoaded()}) // This is the key part: it is basically vanilla JS
image.src = this.src
},
methods:{
onLoaded(){
this.loaded = true
}
},
template: `
<div class="wrapper">
<transition name="fade">
<img class="icon" v-bind:src="src" v-if="loaded">
</transition>
</div>
`
})
new Vue({
el: '#wrapper'
});
.wrapper{
width: 350px;
height: 150px;
background: slategrey;
}
.fade-enter-active {
transition: opacity 3s ease-in-out;
}
.fade-enter-to{
opacity: 1;
}
.fade-enter{
opacity: 0;
}
<script src="https://unpkg.com/vue@2.4.4/dist/vue.js"></script>
<div id="wrapper">
<image-that-fades-in-on-load></image-that-fades-in-on-load>
</div>
最佳答案
您可以使用 v-on:
(或 @
简写)绑定(bind)到任何 DOM 事件的语法。在您的例子中,load
事件在加载图像时触发。
因为您正在以“DOM 方式”加载图像,所以您不能使用 v-if
,因为那样 Vue 将不会渲染该元素(但您需要它,所以图像 src 被获取).相反,您可以使用 v-show
,这将呈现但隐藏该元素。
Vue.component('imageThatFadesInOnLoad', {
data: function() {
return {
src: 'http://via.placeholder.com/350x150',
loaded: false,
}
},
methods: {
onLoaded() {
this.loaded = true;
}
},
template: `
<div class="wrapper">
<transition name="fade">
<img class="icon" v-bind:src="src" v-on:load="onLoaded" v-show="loaded">
</transition>
</div>
`
});
new Vue({
el: '#wrapper'
});
.wrapper {
width: 350px;
height: 150px;
background: slategrey;
}
.fade-enter-active {
transition: opacity 3s ease-in-out;
}
.fade-enter-to {
opacity: 1;
}
.fade-enter {
opacity: 0;
}
<script src="https://unpkg.com/vue@2.4.4/dist/vue.js"></script>
<div id="wrapper">
<image-that-fades-in-on-load></image-that-fades-in-on-load>
</div>
关于javascript - 如何在加载 Vue 时淡入图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47535317/