vue预览pdf vue-pdf 以及使用vue-pdf读取本地文件报错解决方法

前言

需要在页面在线阅读电子书

步骤

step1:

安装

npm install --save vue-pdf

因为是在没有网络的内网开发,所以我是在外网安装的,安装好后拷贝了以下四个文件到项目的 node_modules

vue预览pdf vue-pdf 以及使用vue-pdf读取本地文件报错解决方法_第1张图片

step2:

点击翻页需求

template部分

<template>
  <div class="pdf">
    <p class="arrow">
    // 上一页
    <span @click="changePdfPage(0)" class="turn" :class="{grey: currentPage==1}">Previewspan>
    {
    {currentPage}} / {
    {pageCount}}
    // 下一页
    <span @click="changePdfPage(1)" class="turn" :class="{grey:    			  currentPage==pageCount}">Nextspan>
    p>
     // 加载事件
    pdf>
  div>
template>

script部分

import pdf from 'vue-pdf'
  export default {
     
    components: {
     pdf},
    data () {
     
      return {
     
        currentPage: 0, // pdf文件页码
        pageCount: 0, // pdf文件总页数
        src: '/static/test1.pdf', // pdf文件地址
      }
    },  
    created: {
         
    // 有时PDF文件地址会出现跨域的情况,这里最好处理一下    
    this.src = pdf.createLoadingTask(this.src)
  }
    method: {
     
      // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
      changePdfPage (val) {
     
        // console.log(val)
        if (val === 0 && this.currentPage > 1) {
     
          this.currentPage--
          // console.log(this.currentPage)
        }
        if (val === 1 && this.currentPage < this.pageCount) {
     
          this.currentPage++
          // console.log(this.currentPage)
        }
      },

      // pdf加载时
      loadPdfHandler (e) {
     
        this.currentPage = 1 // 加载的时候先加载第一页
      }

    }
  }

滚动翻页需求

template部分


<template>
  <div class="pdf">
    <pdf
        v-for="currentPage in pageCount"
        :key="currentPage"
        :src="src"
        :page="currentPage"
        @loaded="loadPdfHandler"
      >
      pdf>
  div>
template>

script部分

import pdf from 'vue-pdf'
  export default {
     
    components: {
     pdf},
    data () {
     
      return {
     
        currentPage: 0, // pdf文件页码
        pageCount: 0, // pdf文件总页数
        src: '/static/test1.pdf', // pdf文件地址
      }
    },  
    created: {
           
    this.src = pdf.createLoadingTask(this.src)
  }
    method: {
     
      loadPdfHandler (e) {
     
        this.currentPage = 1 // 加载的时候先加载第一页
        this.pageCount = this.bookPages[this.$route.query.book]
      }

    }
  }

注意:如果pdf在本地,pdf需要放在public文件夹中,引用时不能使用相对路径,且‘/’即表示public文件夹(需略去public)

如 src=" /public/static/book1.pdff" 这样就会报错如下,应该是src="/static/book1.pdf"
在这里插入图片描述

参考文章:https://www.cnblogs.com/steamed-twisted-roll/p/9648255.html

你可能感兴趣的:(vue预览pdf vue-pdf 以及使用vue-pdf读取本地文件报错解决方法)