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>
相关推荐
爱吃鱼的锅包肉6 分钟前
Flutter路由模块化管理方案
前端·javascript·flutter
风清扬雨33 分钟前
Vue3具名插槽用法全解——从零到一的详细指南
前端·javascript·vue.js
海盗强1 小时前
Vue 3 常见的通信方式
javascript·vue.js·ecmascript
大熊猫今天吃什么1 小时前
【一天一坑】空数组,使用 allMatch 默认返回true
前端·数据库
!win !1 小时前
Tailwind CSS一些你需要记住的原子类
前端·tailwindcss
前端极客探险家1 小时前
打造一个 AI 面试助手:输入岗位 + 技术栈 → 自动生成面试问题 + 标准答案 + 技术考点图谱
前端·人工智能·面试·职场和发展·vue
橘子味的冰淇淋~2 小时前
【解决】Vue + Vite + TS 配置路径别名成功仍爆红
前端·javascript·vue.js
利刃之灵2 小时前
03-HTML常见元素
前端·html
kidding7232 小时前
gitee新的仓库,Vscode创建新的分支详细步骤
前端·gitee·在仓库创建新的分支
听风吹等浪起2 小时前
基于html实现的课题随机点名
前端·html