vueshowpdf 移动端pdf文件预览

1、安装

javascript 复制代码
npm install vueshowpdf -S

2、参数

属性 说明 类型 默认值
v-model 是否显示pdf - -
pdfurl pdf的文件地址 String -
scale 默认放大倍数 Number 1.2
minscale 最小放大倍数 Number 0.8
maxscale 最大放大倍数 Number 2

3、事件

名称 说明 回调参数
closepdf pdf关闭事件 -
pdferr 文件地址解析错误事件 -

4、核心代码

html 复制代码
<template>
  <div class="case-info">
    <van-cell title="附件" value="预览" is-link @click="viewPdf" class="perview" />
    <vueshowpdf class="pdf" v-model="isShowPdf" :pdfurl="pdfurl"
      :minscale='0.4' :scale='0.6' @closepdf="isShowPdf = false" @pdferr="pdfError"
    ></vueshowpdf>
  </div>
</template>

<script>
import api from '@/api.js'
import vueshowpdf from 'vueshowpdf'
export default {
  name: 'test',
  data () {
    return {
      isShowPdf: false,
      pdfUrl: '',
      pdfKey: 0
    }
  },
  components: {
    vueshowpdf
  },
  deactivated () {
    // 离开页面默认关闭pdf
    this.isShowPdf = false
    this.pdfKey++
  },
  methods: {
    // 预览pdf
    async viewPdf () {
      if (this.pdfUrl) {
        this.isShowPdf = true
      } else {
        this.$toast.loading({
          message: '加载中...',
          duration: 0,
          forbidClick: true
        })
        try {
          const res = await api.getFilePreview()
          this.$toast.clear()
          if (res.code === '0') {
            let blob = this.dataURLtoBlob(res.data)
            this.pdfurl = URL.createObjectURL(blob)
            this.isShowPdf = true
          } else {
            this.$toast(res.msg || '该原始文件不存在')
          }
        } catch (error) {
          this.$toast.clear()
        }
      }
    },
    // 将base64转换为文件
    dataURLtoBlob (dataurl) {
      const bstr = atob(dataurl)
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: 'application/pdf' })
    },
    // 关闭pdf
    closePdf () {
      this.isShowPdf = false
      this.pdfKey++
    },
    // pdf预览失败
    pdfError (errorUrl) {
      this.$toast.fail('预览失败')
      this.isShowPdf = false
      this.pdfKey++
    }
  }
}
</script>

<style lang="scss" scoped>
  .perview .van-cell__value {
    color: #468bff;
    text-decoration: underline;
  }
</style>
相关推荐
老虎06272 分钟前
JavaWeb前端(HTML,CSS具体案例)
前端·css·html
Mintopia8 分钟前
一个月速成 AI 工程师:从代码小白到智能工匠的修炼手册
前端·javascript·aigc
Mintopia11 分钟前
Next.js 全栈:接收和处理请求
前端·javascript·next.js
袁煦丞1 小时前
2025.8.18实验室【代码跑酷指南】Jupyter Notebook程序员的魔法本:cpolar内网穿透实验室第622个成功挑战
前端·程序员·远程工作
Joker Zxc1 小时前
【前端基础】flex布局中使用`justify-content`后,最后一行的布局问题
前端·css
无奈何杨1 小时前
风控系统事件分析中心,关联关系、排行、时间分布
前端·后端
Moment1 小时前
nginx 如何配置防止慢速攻击 🤔🤔🤔
前端·后端·nginx
晓得迷路了1 小时前
栗子前端技术周刊第 94 期 - React Native 0.81、jQuery 4.0.0 RC1、Bun v1.2.20...
前端·javascript·react.js
HAPPY酷1 小时前
给纯小白的Python操作 PDF 笔记
开发语言·python·pdf