javascript - 如何在加载 Vue 时淡入图像

标签 javascript vuejs2

我创建了这个组件,它在图像加载到客户端后淡入淡出。我认为有一种更像 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">&nbsp;
      </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">&nbsp;
      </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/

相关文章:

javascript - 内部 html 不使用我的链接样式表

javascript - 在挂载的钩子(Hook)函数中初始化Viewer.js。 (错误 : The first argument is required and must be an element)

javascript - 无法使 JavaScript 工作,是 ID 问题吗?

Javascript 不更新 h :inputHidden 的值

javascript - 我的循环创建了谷歌地图标记,但它无法正确设置它们的位置,因此它们不会被显示。硬编码位置有效

laravel-5 - 使用 laravel、Socket 和 Redis 动态更改 channel

javascript - 我的自定义 ShopWare 6 Javascript 插件中未定义“Vue”

ajax - 获取组件在渲染之前等待异步数据

javascript - 如何使用 Javascript 在下拉列表中显示时间表?

javascript - 使用 expo-constants 和额外属性来 react native Jest 测试