html

  <pdf v-for="i in numberPage" :key="i" :src="pdfUrl" :page="i" style="width:100%;height:auto" />

js

<script>
import pdf from 'vue-pdf'
export default {
 data() {
    return {
      pdfUrl: '',
      numberPage: 0
    }
  },
  created() {
    this.preview(this.$route.params.id)
  },
   methods: {
    preview(fileId) {
      const params = { fileId: fileId }
      const FUNCTION = 'preview'
      this.preview(params, FUNCTION).then(res => {
        this.loading = false // 取消加载
        if (res.size === 0) {
          this.$notify({
            title: '文件不存在',
            type: 'error',
            duration: 2500
          })
        } else {
          this.pdfUrl = this.getObjectURL(res) // 解析出pdfUrl   **注意:如果在res中拿到的便是url,则这一步可以跳过
          const loadingTask = pdf.createLoadingTask(this.pdfUrl)
          // 注意这里一定要这样写
          loadingTask.promise.then(load => {
            this.numberPage = load.numPages
          }).catch(err => {
            console.log(err)
          })
        }
      }).catch(err => {
        this.loading = false // 取消加载
        console.log(err)
        this.$notify({
          title: 'pdf预览出错',
          type: 'error',
          duration: 2500
        })
      })
    },
    // 将返回的流数据转换成url
    getObjectURL(file) {
      let url = null
      if (window.createObjectURL !== undefined) { // basic
        url = window.createObjectURL(file)
      } else if (window.webkitURL !== undefined) { // webkit or chrome
        try {
          url = window.webkitURL.createObjectURL(file)
        } catch (error) {
          console.log(error)
        }
      } else if (window.URL !== undefined) { // mozilla(firefox)
        try {
          url = window.URL.createObjectURL(file)
        } catch (error) {
          console.log(error)
        }
      }
      return url
    }
  }
}
</script>

更加具体的使用
https://download.csdn.net/download/m0_38010595/14141574

解决vue中使用vue-pdf插件提示 window is not defined

// webpack.config.js 或 webpack.base.conf.js
module.exports = {
    // 此处省略部分配置项
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
        globalObject: "this"        // 关键在此项配置,需要配置为 "this", 默认为 "window"
    },
    // 此处省略部分配置项
}
Logo

前往低代码交流专区

更多推荐