前端入门之(vue图片加载框架一)

本文介绍了如何基于Vue实现一个简单的图片加载框架。通过监听图片加载状态,实现加载中显示loading图片,加载失败显示默认错误图片的功能。文章逐步讲解了如何封装指令、创建 Lazy 类和 LazyListener 类,并通过实例演示了其工作原理。
摘要由CSDN通过智能技术生成

前言: 之前做android的时候,会接触各种图片加载框架,也自己封装过,封装网络框架目的无非就是为了提高图片的复用性、减少内存消耗、监听图片的加载过程等等.换成web前端其实是一样的操作,好啦! 说了那么多我们来简单的实现一个图片加载框架,小伙伴跟紧了哦!!!

因为一直在做vue,所以我就以vue为基础来开发我们的图片加载框架了,我们新见一个vue项目,然后运行(我就以之前的vuex的demo为例子了,感兴趣的童鞋可以看看我之前写的vuex的几篇文章).

<template>
  <div class="opt-container">
    <img :src="images[0]">
  </div>
</template>

<script>
  export default {
    name: 'Lazy',
    data() {
      return {
        images: [
          'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283186&di=c136f7387cfe2b79161f2f93bff6cb96&imgtype=0&src=http%3A%2F%2Fpic1.cxtuku.com%2F00%2F09%2F65%2Fb3468db29cb1.jpg',
          'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283186&di=de941561df3b6fd53b2df9bfd6c0b187&imgtype=0&src=http%3A%2F%2Fpic43.photophoto.cn%2F20170413%2F0008118236659168_b.jpg',
          'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283185&di=aff7e8aa60813f6e36ebc6f6a961255c&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01d60f57e8a07d0000018c1bfa2564.JPG%403000w_1l_2o_100sh.jpg',
        ]
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .opt-container {
    font-size: 0px;
  }
</style>

可以看到,很简单! 我们就是放了一个img标签.然后加载了一张图片:
这里写图片描述

现在有一个这样的需求,因为我们的图片比较大,所以当图片正在加载的时候,我们显示loading图片,然后当我们图片加载失败的时候,我们显示一个失败的默认图,当我们图片正在加载成功的时候,我们再显示.

我们来试一下哈~~

我们定义一个方法,叫loadImageAsync:

 loadImageAsync(item, resolve, reject) {
        let image = new Image();
        image.src = item.src;

        image.onload = function () {
   
          resolve({
            naturalHeight: image.naturalHeight,
            naturalWidth: image.naturalWidth,
            src: image.src
          });
        };

        image.onerror = function (e) {
   
          reject(e)
        };
      }
    }

代码很简单,我就不解释了~~ ,接下来是在我们的created的时候调用此方法:

 created() {
      let item = {
  src: this.images[0]};
      this.loadImageAsync(item,(response)=>{
        console.log('图片加载成功');
        console.log('图片的宽度为:'+response.naturalWidth);
        console.log('图片的高度为:'+response.naturalHeight);
      },(error)=>{
        console.log('图片加载失败');
      });
    }

我们重写运行代码看log:

[HMR] Waiting for update signal from WDS...
Lazy.vue?2392:40 图片加载成功
Lazy.vue?2392:41 图片的宽度为:600
Lazy.vue?2392:42 图片的高度为:398

我们可以看到,log里面打印出来了日志,然后把图片的宽高都打印出来了,我们试着把图片链接写错试一下:

created() {
        //我们把链接写错
      let item = {
  src: 11111+this.images[0]};
      this.loadImageAsync(item,(response)=>{
        console.log('图片加载成功');
        console.log('图片的宽度为:'+response.naturalWidth);
        console.log('图片的高度为:'+response.naturalHeight);
      },(error)=>{
        console.log('图片加载失败');
      });
    }

重新运行代码:

[HMR] Waiting for update signal from WDS...
Lazy.vue?2392:44 图片加载失败

可以看到,图片加载失败了~~

好啦,有了图片的监听,我们就可以操作了,我们首先准备两张图片,一张为loading(加载中图片),一张为erro(加载失败的图片).

这里写图片描述

然后我们动态的给img标签设置上src:

<template>
  <div class="opt-container">
    <img :src="currSrc">
  </div>
</template>

<script>
  const errorImg = require('./error.png');
  const loadingImg = require('./loading.png');
  export default {
    name: 'Lazy',
    data() {
      return {
        images: [
          'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283186&di=c136f7387cfe2b79161f2f93bff6cb96&imgtype=0&src=http%3A%2F%2Fpic1.cxtuku.com%2F00%2F09%2F65%2Fb3468db29cb1.jpg',
          'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283186&di=de941561df3b6fd53b2df9bfd6c0b187&imgtype=0&src=http%3A%2F%2Fpic43.photophoto.cn%2F20170413%2F0008118236659168_b.jpg',
          'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533137283185&di=aff7e8aa60813f6e36ebc6f6a961255c&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01d60f57e8a07d0000018c1bfa2564.JPG%403000w_1l_2o_100sh.jpg',
        ],
        currSrc: loadingImg  //默认为加载中状态
      }
    },
    methods: {
      loadImageAsync(item, resolve, reject) {
        let image = new Image();
        image.src = item.src;

        image.onload = function () {
    
          resolve({
            naturalHeight: image.naturalHeight,
            naturalWidth: image.naturalWidth,
            src: image.src
          });
        };

        image.onerror = function (e) {
    
          reject(e)
        };
      }
    },
    created() {
      let item = {src: this.images[0]};
      this.loadImageAsync(item, (response) => {
        console.log('图片加载成功');
        console.log('图片的宽度为:' + response.naturalWidth);
        console.log('图片的高度为:' + response.naturalHeight);

        //当图片加载成功的时候,把图片的src换成目标地址
        this.currSrc = response.src;
      }, (error) => {
        console.log('图片加载失败');
        //当图片加载失败的时候,把图片的src换成失败的图片
        this.currSrc = errorImg;
      });
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .opt-container {
    font-size: 0px;
  }
</style>

代码都有注释,小伙伴应该看得懂哈~~我们运行一下:
这里写图片描述

太快了,录屏看不出loading的效果,我们把图片链接改错试试:

 let item = {src: 1111+this.images[0]};

这里写图片描述

可以看到,我们的图片加载失败就显示了一张失败的默认图,好啦! 到这里我们的简单的需求算是实现了,这时,有小伙伴就要说了,你这也太麻烦了,我只有一张图片还好,既然是框架,那就得是针对整个工程, 是的!! 我们就封装一下我们的代码,最后实现的时候,我们只需要这样写就好了:

<template>
  <div class="opt-container">
    <img v-lazy="{src:images[0]}">
  </div>
</template>

我们通过指令的形式来加载我们的图片,然后在指令中去切换图片状态,没看过指令的童鞋自己去看官网哈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值