Vue项目中,利用iframe在线预览pdf/图片等

在components下新建 src\components\iFrame\index.vue

<template>
    <div v-loading="loading" :style="'height:' + height">
        <iframe :src="src" frameborder="no" style="width: 100%; height: 100%" scrolling="auto" />
    </div>
</template>
<script>
export default {
    props: {
        src: {
            type: String,
            required: true
        },
    },
    data() {
        return {
            height: document.documentElement.clientHeight - 94.5 + "px;",
            loading: true,
            url: this.src
        };
    },
    mounted: function () {
        setTimeout(() => {
            this.loading = false;
        }, 300);
        const that = this;
        window.onresize = function temp() {
            that.height = document.documentElement.clientHeight - 94.5 + "px;";
        };
    }
};
</script>

在components下新建 src/components/FilePreview/index.vue

<template>
    <el-dialog :title="title" :visible.sync="visible" @close="visible = false" :width="width" append-to-body v-dialogDrag :close-on-click-modal="false">
        <div :style="[{height:`${height}px`}]" class="styleObj">
            <template>
                <i-frame :src="url" />
            </template>
        </div>
    </el-dialog>
</template>

<script>
import iFrame from "@/components/iFrame/index";
export default {
    props: {
        //宽
        width: {
            type: String,
            default: '60%',
        },
        //高
        height: {
            type: Number,
            default: 500,
        },
        //标题
        title: {
            type: String,
            default: '文件预览',
        }
    },
    name: "FilePreview",
    components: { iFrame },
    data() {
        return {
            visible: false,
            url: ''
        };
    },
    methods: {
        preview(fileUrl) {
            if (fileUrl) {
                this.url = fileUrl;
                this.visible = true
            } else {
                this.$modal.msgError("文件不存在!");
            }
        },
    }
};
</script>

<style scoped>
.styleObj {
    overflow: auto;
}
</style>

在组件中引用

<template>
    <div>
        <!-- 其余代码省略 -->
        <FileViewer ref="FileViewer" :width="`80%`" :height="700"/>
    </div>
</template>

<script>
import FileViewer from "@/components/FilePreview"
export default {
    components: { FileViewer },
    data() {
        return {},
    },
    mounted(){
        let url = "文件路径";
        this.$refs.FileViewer.preview(url);
    }
}
</script>

效果如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值