【vue】使用URL.createObjectURL() 和懒加载优化加载图片的技巧


前言

提示:有很多项目中会有加载图片的功能,有时候由于各种原因吧,图片可能加载不出来—懒加载。


提示:以下是本篇文章正文内容,下面案例可供参考

一、功能介绍

示例:小编介绍的是左侧是菜单栏右侧是显示的封面图片。

在这里插入图片描述

事件

   check2(row, index) {
      this.rowTypeName = row.noticeTypeName
      sessionStorage.setItem("left_isActive", index);
      this.isActive = index;
      if(row.noticeTypeName == "全部公告"){
        (this.isshow = true), (this.onshow = false);
      this.initialization()
      }else{
        (this.isshow = true), (this.onshow = false);
        this.$axios({
        method: "POST",
        url: http_infor() + "/v1.0/zg_common_service/queryPortalNoticeInfo",
        data: {
          queryInfo: {
            pageNum: this.pages2,
            pageSize: this.page_num2,
            filters: [
              {
                fieldName: "portalNoticeType.noticeTypeName",
                operator: "EQ",
                fieldValue: row.noticeTypeName,
              },
            ],
            sorters: [
              {
                sortField: "createTime",
                direction: "DESC",
              },
            ],
            connectOperator: "AND",
          },
        },
        connectOperator: "AND",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-Auth-Token": sessionStorage.getItem("token"),
        },
      })
        .then((res) => {
          this.pagetotal = res.data.total
          res.data.root.forEach((item) =>{
            console.log(item)
            this.$axios({
              method: "GET",
              url: http_infor() + "/v1.0/zg_common_service/getPortalNoticeInfoPicture?portalNoticeInfoId=" + item.id ,
              responseType:'blob',
              headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
                "X-Auth-Token": sessionStorage.getItem("token"),
              },
            })
              .then((res2) => {
                console.log(res2.config.url )
                item.contentSource = res2.config.url
                console.log(res)
                var that = this
                //  通过blob格式下载流文件
                that.imageUrl = window.URL.createObjectURL(res2.data);  
              })
              .catch((error) => {
                // console.log(error);
              });
          }
          )
          this.boxlist = res.data.root;
          if (res.data.total == 0) {
            this.nozanwu = true;
          } else {
            this.nozanwu = false;
          }
        })
        .catch((error) => {
          // console.log(error);
        });
      }
    },

二、URL.createObjectURL()

URL.createObjectURL() 静态方法会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL
的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。

URL.createObjectURL(blob)和FileReader.readAsDataURL(file)很相似,

通过URL.createObjectURL(blob)可以获取当前文件的一个内存URL
但是小编这里有些问题,就是使用这个方法可以实现,出现了一个致命问题没考虑图片是循环出来的,这样一系列操作后,拿到的单张图片,所以最后在循环中找问题,看看是哪里的错误,我是通过在循环数据里找了一个空的字段,然后使用 responseType:‘blob’, 这种方式,把url这个路径给了他,前端页面再次循环就可以显示了
代码如下(示例):

懒加载

在开发中,有一些页面以图片展示为主,界面不可见部分可能有很多图片用户并不会去看,而且图片消耗的流量十分多,必须要优化。推荐使用懒加载,有时候使用各种npm包即可解决,就比如前不久我们在登录需要保密性和·那个安全性上的一个加密,后端给了一堆文件搞了半天最后通过一个sm3的npm包解决了,哦买噶!!!
言归正传介绍下懒加载的使用

  1. vue 安装 lazyload
npm i vue-lazyload -s
  1. main.js 全局配置
import VueLazyload from 'vue-lazyload'
 
Vue.use(VueLazyload, {
  preLoad: 1.3, //预加载高度
  error: require('../static/img/error.jpg'), //没加载成功错误展示图片 
  loading: require('../static/img/loading.gif'), //加载等待图片
  attempt: 1 //尝试次数
})
  1. 使用 src 改为 v-lazy
    在这里插入图片描述
   <img v-lazy="item.contentSource" alt="" />

总结

:以上就是今天要讲的内容,本文仅仅简单介绍了加载图片的方法,而vue提供了大量能使我们快速便捷地处理数据的函数和方法,如有其他问题欢迎探讨。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码

)">
< <上一篇
)">
下一篇>>