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>
相关推荐
anOnion6 小时前
构建无障碍组件之Carousel Pattern
前端·html·交互设计
ssshooter6 小时前
Tauri 2 iOS 开发避坑指南:文件保存、Dialog 和 Documents 目录的那些坑
前端·后端·ios
Можно7 小时前
深入理解 ES6 Proxy:与 Object.defineProperty 的全面对比
前端·javascript·vue.js
Birdy_x7 小时前
接口自动化项目实战(1):requests请求封装
开发语言·前端·python
天天向上10248 小时前
vue el-table实现拖拽排序
前端·javascript·vue.js
柳杉9 小时前
Three.js × Blender:从建模到 Web 3D 的完整工作流深度解析
前端·javascript·数据可视化
reembarkation10 小时前
vue3中使用howler播放音频列表
前端·vue.js·音视频
手握风云-10 小时前
基于 Java 的网页聊天室(三)
服务器·前端·数据库
weixin1997010801611 小时前
《识货商品详情页前端性能优化实战》
前端·性能优化
Forever7_11 小时前
重磅!Vue3 手势工具正式发布!免费使用!
前端·前端框架·前端工程化