干货--手把手撸vue移动UI框架: 图片预加载

473 阅读2分钟
原文链接: www.divpc.cn
chenyq 2018/06/05 16:13:15 干货--手把手撸vue移动UI框架: 图片预加载

前言

图片预加载:顾名思义,图片预加载就是在网页全部加载之前,提前加载图片。我们这个插件很简单,主要做一件事情:当图片加载的过程中加载失败,或者路径不存在或者路径为空的时候,显示我们默认的图片;如果图片正确加载就显示原本的图片。这样就避免图片加载失败的时候页面上出现裂图或者是空白,提升用户体验。

实现代码

具体的代码如下:

<template>
  <img class="r-image" :src="dataSrc">
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      dataSrc: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA1tpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0iMUIyMEJBRUQwMDNCODlBQ0MxRTQ1NEEyM0YyRDlCNkUiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RUJGRjEwMDg1QjQ2MTFFODhBNjhFRkI3NUU0QjQ1QTEiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RUJGRjEwMDc1QjQ2MTFFODhBNjhFRkI3NUU0QjQ1QTEiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NmNjYTUwZGMtMzViNi00YTNiLWFmZGItNmZhOTQyYzM3NjA1IiBzdFJlZjpkb2N1bWVudElEPSIxQjIwQkFFRDAwM0I4OUFDQzFFNDU0QTIzRjJEOUI2RSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PqAzJzYAAACiSURBVHja7NAxAQAACAMgtX++5bGCnw9EoJMUN6NAlixZsmTJUiBLlixZsmQpkCVLlixZshTIkiVLlixZCmTJkiVLliwFsmTJkiVLlgJZsmTJkiVLgSxZsmTJkqVAlixZsmTJUiBLlixZsmQpkCVLlixZshTIkiVLlixZCmTJkiVLliwFsmTJkiVLlgJZsmTJkiVLgSxZsmTJkqVAlqxvK8AAT4MDSiSPlvcAAAAASUVORK5CYII='
    }
  },
  methods: {
    init () {
      /* eslint-disable no-new */
      let img = new Image()
      img.src = this.src
      img.onload = () => {
        this.dataSrc = this.src
      }
    }
  },
  created () {
    this.init()
  }
}
</script>

其实代码很简单,给图片一张默认的图片,然后创建一个Image对象,用来加载图片,如果图片加载成功触发onload函数,改变图片的路径,这样就实现了一个图片预加载组件了。是不是很简单?