前端实现图片预览的两种方式及使用

A.URL.createObjectURL

     就是将用户通过文件上传表单元素,所选择的图片 读取到内存当中

     并且返回这个图片的url地址,将来就可以将url地址设置给src属性用来展示图片

    createObjectURL 方法的特点就是他的执行方法是同步的

B.FileReader 对象

    使用FileReader对象读取文件上传表单元素,选择的图片,并且生成一个base64的字符将来就可以将base64的字符串设置给图片的src属性,用来做图片的预览

    FileReader对象的使用特点就是执行方式是异步的

 另一种方法详解

  有了方法但是我们先从需求分析:实现思路

  1. 从文章内容中获取到所有的 img DOM 节点

  2. 获取文章内容中所有的图片地址

  3. 遍历所有 img 节点,给每个节点注册点击事件

  4. img 点击事件处理函数中,调用 ImagePreview 预览

     我们运用了vant-ui组件中的ImagePreview 图片预览

import { ImagePreview } from 'vant'  
// 按需加载 全局加载不需要写 我这里写是为了突出方法 ImagePreview
 ImagePreview(['https://img.yzcdn.cn/vant/apple-1.jpg'])  // 直接运用方法

正文: 

1.给文章详情元素绑定 ref 属性

<div ref="article-content" class="article-content" v-html="article.content"></div>

2.封装 ImagePreview 预览图片方法

// 预览图片
previewImage() {
  // 得到所有的 img 节点
  const articleContent = this.$refs['article-content']
  const imgs = articleContent.querySelectorAll('img')
  const images = []

  imgs.forEach((item, index) => {
    images.push(item.src)

    item.onclick = () => {
      ImagePreview({
        images: images,
        startPosition: index
      })
    }
  })
}

3.在页面加载成功中,调用 ImagePreview 预览方法

setTimeout(() => {
  this.previewImage()
})

  完毕!

原文地址:https://www.cnblogs.com/wsm777/p/13861156.html