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>
相关推荐
MiyueFE31 分钟前
14 个逻辑驱动的 UI 设计技巧,助您改善任何界面
前端·设计
啃火龙果的兔子35 分钟前
前端单元测试覆盖率工具有哪些,分别有什么优缺点
前端·单元测试
「、皓子~1 小时前
后台管理系统的诞生 - 利用AI 1天完成整个后台管理系统的微服务后端+前端
前端·人工智能·微服务·小程序·go·ai编程·ai写作
就改了1 小时前
Ajax——在OA系统提升性能的局部刷新
前端·javascript·ajax
凌冰_1 小时前
Ajax 入门
前端·javascript·ajax
京东零售技术1 小时前
京东小程序JS API仓颉改造实践
前端
老A技术联盟2 小时前
从小白入门,基于Cursor开发一个前端小程序之Cursor 编程实践与案例分析
前端·小程序
风铃喵游2 小时前
构建引擎: 打造小程序编译器
前端·小程序·架构
sunbyte2 小时前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | ThemeClock(主题时钟)
前端·javascript·css·vue.js·前端框架·tailwindcss
小飞悟2 小时前
🎯 什么是模块化?CommonJS 和 ES6 Modules 到底有什么区别?小白也能看懂
前端·javascript·设计