ElementUI 图片文件预览插件封装
ImgViewer.vue
<template> <Dialog title="图片预览" :visible.sync="dialogVisible" :append-to-body="true" @closed="dialogImageUrl = ''"> <img v-if="dialogImageUrl" style="max-width:100%;display:block;margin:0 auto;" width="100%" :src="dialogImageUrl" alt=""> </Dialog> </template> <script> import { Dialog } from 'element-ui' export default { name: 'FlowImgViewer', components: { Dialog }, props: {}, data() { return { dialogVisible: false, dialogImageUrl: '' } }, created() {}, mounted() {}, methods: { openFile(file) { const imgList = ['gif', 'jpg', 'jpeg', 'png'] const filePath = file.name const index = filePath.lastIndexOf('.') // 获取后缀 const ext = filePath.substr(index + 1).toLowerCase() if (imgList.includes(ext)) { this.dialogImageUrl = file.url this.dialogVisible = true return null } if (ext === 'pdf') { window.open(file.url, file.name) } else { try { this.download(file.url, file.name) } catch (err) { window.open(file.url) } } // window.open(file.url, file.name) }, download(url, filename) { getBlob(url, function(blob) { saveAs(blob, filename) }) function getBlob(url, cb) { var xhr = new XMLHttpRequest() xhr.open('GET', url, true) xhr.responseType = 'blob' xhr.onload = function() { if (xhr.status === 200) { cb(xhr.response) } } xhr.send() } function saveAs(blob, filename) { if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, filename) } else { var link = document.createElement('a') var body = document.querySelector('body') link.href = window.URL.createObjectURL(blob) link.download = filename link.style.display = 'none' body.appendChild(link) link.click() body.removeChild(link) window.URL.revokeObjectURL(link.href) } } } } } </script> <style lang="scss" scoped> </style>
fileViewer.js
// 文件下载和图片预览
import Vue from 'vue'
import dialog from './ImgViewer.vue'
// 使用extend继承创建组件
const Cmp = Vue.extend(dialog)
export default new Cmp().$mount()
全局引入
import fileViewer from './fileViewer'
Vue.prototype.$fileView = fileViewer
使用方法
this.$fileView.openFile({ url: file.url, name: file.fileName })