移动端vue2使用vue-pdf当前页面预览(优化为滑动翻页)

该文章描述了一个使用Vue.js和vue2-touch-events插件在移动端优化PDF预览的过程。通过将点击翻页改为滑动翻页,提升了用户体验。同时,应用了节流函数处理swipe事件,确保了滑动操作的流畅性。此外,文章还涉及了PDF加载、错误处理及页面导航的实现。
摘要由CSDN通过智能技术生成

1.基于上次的优化处理,移动端进行点击翻页,感觉很怪,于是继续进行优化,改为滑动翻页

2.使用 :vue2-touch-events 插件

### main.js 引入并注册

import Vue2TouchEvents from "vue2-touch-events";
Vue.use(Vue2TouchEvents,{
    disableClick:true,
    swipeTolerance:50,
    namespace:"touch"
})

### 模板

<template>
    <div class="page">
		<MyHeader pageTitle="PDF预览" :backPre="true" :downMenu="false"/>
		<div class="content">
			<Loading v-if="loading"></Loading>
			<!-- pdf组件多页显示(一次性都出来) -->
			<!-- <div class="pdf" v-for="i in numPages" :key="i">
					<pdf ref="pdf" :src="src" :page="i"></pdf>
				</div> -->

			<pdf 
				ref="pdf"
				:src="src"
				:page="numPages"
				@progress="loadedRatio=$event"
                @num-pages="pageTotalNum=$event"
                @error="pdfError($event)"
                @loaded="loadHandler"
                @page-loaded="pageLoaded($event)"
                v-touch:swipe.left.prevent.stop="swipeLeftHandler_th"
                v-touch:swipe.right.prevent.stop="swipeRightHandler_th"
                >
            </pdf>
            <div class="pdfBtn">
               <vant-button
                    round
                    type="info"
                    size="small"
                    @click="prePage"
                    :class="showBtn ? 'active' : 'notActive'"
                    :disabled="isDisableLeft"
                    v-show="showBtnAgainLeft">
                    上一页
               </van-button>
               <vant-button
                    round
                    type="info"
                    size="small"
                    @click="nextPage"
                    :class="showBtn ? 'active' : 'notActive'"
                    :disabled="isDisableLeft"
                    v-show="showBtnAgainLeft">
                    下一页
               </van-button>
            </div>
             <!-- <div class="control-box">
                    <button
                    	:class="{select:idx=0}"
                    	@touchstart="idx=0"
                    	@touchend="idx=-1"
                    	@click="scaleD">
                    放大
                    </button>
                    <button
                    	:class="{select:idx==1}"
                    	@touchstart="idx=1"
                    	@touchend="idx=-1"
                    	@click="scaleX">
                    缩小
                    </button>
                  </div> -->
		</div>
	</div>
</template>

### js代码

<script>
import axios from "axios";
import throttle from "lodash/throttle"; //按需引入节流函数
import vuePdf from "vue-pdf";
const pdf = {...vuePdf,destroyed:undefined}; //解决加载后页面空白问题
// import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";// 解决中文加载问题
export default{
    name:"DownloadServiceManul",
    data(){
        return{
            numPage:1,//当前页码数
            url:"",//基础地址
            path:"",//pdf动态路径,例: /testFile.pdf
            src:"",
            scale:100,//放大系数
            idx:-1,
            loading:true,
            loadedRatio:0,// 加载进度
            pageTotalNum:1,// 总页数
            curPageNum:0,
            showBtn:false,
            isDisableLeft:true,
            isDisableRight:false,
            showBtnAgainLeft:false,
            showBtnAgainRight:true,
            page:1
        };
    },
    props:{
        propsData:[Object]
    },
    components:{
        pdf
    },
    methods:{
        //初始化
        initPDF(){
            const {fileId} = this.propsData;
            //this.url="/cpic-health-ecs-eservice/api";
            this.url = axios.defaults.baseURL;
            this.path = `/downloadServiceManul?fileId=${fileId}&v=${Date.now()}`;
            this.src = pdf.createLoadingTask({
                url : this.url + this.path,//动态
                cMapUrl : "/cmaps/",
                cMapPacked : true
            });
            /* 直接展示全部pdf的使用代码(不是分页的)*/
           /* this.src.promise.then(pdf => {
                this.numPages = pdf.numPages;
                this.loading = false;
            })*/
            
            //加载完PDF后对缓存进行清除
            for(var key in require.cache){
                if(key.indexOf("bcmap") >= 0){
                    delete require.cache[key];
                }
            }
        },
        //PDF渲染完函数
        loadHandler(){
            this.showBtn = true;
        },
        //上一页
        prePage(){
            this.numPages = this.page;
        },
        //下一页
        nextPage(){
            this.numPages = this.page;
        },
        //页面加载完
        pageLoaded(e){
            this.numPages = e;
            this.loading = false;
        },
        //PDF加载错误
        pdfError(error){
            console.log(error);
            return Promise.reject(error);
        },
        //左滑事件(节流优化)
        swipeLeftHandler_th:throttle(function swipeLeftHandler(){
            if(this.pageTotalNum > 1){
               //边界轻提示
                this.$toast({
                    message:"当前只有一页!"
                    duration:0,
                    overlay:true
                });
                //轻提示存在时间
                let second = 1;
                const timer = setInterval(()=>{
                    second--;
                    if(!second){
                        clearInterval(timer);
                        //手动清除 Toast
                        this.$toast.clear();
                    }
                },1000);
                return false;
            }
             this.page = this.numPages;
            if(this.page == this.pageTotalNum){
                //边界轻提示
                this.$toast({
                    message:"已经没有了!"
                    duration:0,
                    overlay:true
                });
                //轻提示存在时间
                let second = 1;
                const timer = setInterval(()=>{
                    second--;
                    if(!second){
                        clearInterval(timer);
                        //手动清除 Toast
                        this.$toast.clear();
                    }
                },1000);
                return false;
            }
            this.page = this.page < this.pageTotalNum ? this.page + 1 : this.pageTotalNum;
        },1000,{
            trailing:false
        }),
          //右滑事件(节流优化)
        swipeRightHandler_th:throttle(function swipeRightHandler(){
            if(this.pageTotalNum <= 1){
               //边界轻提示
                this.$toast({
                    message:"当前只有一页!"
                    duration:0,
                    overlay:true
                });
                //轻提示存在时间
                let second = 1;
                const timer = setInterval(() =>{
                    second--;
                    if(!second){
                        clearInterval(timer);
                        //手动清除 Toast
                        this.$toast.clear();
                    }
                },1000);
                return false;
            }
             this.page = this.numPages;
            if(this.page <= 1){
                //边界轻提示
                this.$toast({
                    message:"这里是首页!"
                    duration:0,
                    overlay:true
                });
                //轻提示存在时间
                let second = 1;
                const timer = setInterval(()=>{
                    second--;
                    if(!second){
                        clearInterval(timer);
                        //手动清除 Toast
                        this.$toast.clear();
                    }
                },1000);
                return false;
            }
            this.page = this.page > 1 ? this.page - 1 : 1;
        },1000,{
            trailing:false
        }),
        //放大
        /*scaleD(){
            this.scale += 5;
            const pdfDomList = this.$refs.pdf;
            pdfDomList.forEach(pdf => {
                pdf.$el.style.width = parseInt(this.scale) + "%";
            })
        },*/
        //缩小
          /*scaleX(){
              if(this.scale == 100) return;
            this.scale += -5;
            const pdfDomList = this.$refs.pdf;
            pdfDomList.forEach(pdf => {
                pdf.$el.style.width = parseInt(this.scale) + "%";
            });
        }*/
    },
    watch:{
        //监视page变化,滑动时调用绑定在上下页按钮的事件函数
        page:{
            handler(newVal,oldVal){
                if(newVal > oldVal){
                    this.prePage();
                }else if (newVal < oldVal){
                    this.nextPage();
                }
            }
        }
    },
    mounted(){
        this.initPDF();
    }
}
</script>

### 样式代码

<style lang="less" scoped>
.content{
    bottom:0;
    .pdfBtn{
        display: flex;
        justify-content: space-around;
        margin-top: 1rem;
    }
    .control-box{
        position: fixed;
        right: 20px;
        bottom: 35px;
    }
    .active{
        display: block;
    }
    .notActive{
        display: none;
    }
}
</style>

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值