最近的后台项目需要用到图片预览功能,因涉及到多种业务场景,索性写了一个全局能调用的图片预览。
话不多说,直接开干!
1.先通过element-ui引入它内置图片预览组件
// preview.vue
<template>
<el-image-viewer
v-if="showPreview"
:urlList="previewImages"
:on-close="closeViewer"
></el-image-viewer>
</template>
<script>
// 可自行去对应目录查看该组件
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
export default {
data() {
return {
showPreview: false,
previewImages: []
};
},
components: {
ElImageViewer
},
methods: {
closeViewer() {
this.showPreview = false;
}
}
};
</script>
2.在Vue上注册全局调用的方法
// preview.js
import PreviewItem from "./preview.vue";
const Preview = {};
// 注册
Preview.install = function(Vue) {
const PreviewConstructor = Vue.extend(PreviewItem);
const instance = new PreviewConstructor();
instance.$mount(document.createElement("div"));
document.body.appendChild(instance.$el);
/**
* 挂载在vue原型上
* @param {Array} imgs 需要预览的图片数组
*/
Vue.prototype.$openPreview = function(imgs = []) {
instance.showPreview = true;
instance.previewImages = imgs;
};
};
export default Preview;
3.在main.js文件中引入
import Preview from "@/components/PreviewItem/preview.js";
Vue.use(Preview);
准备完毕,我们就可以开始使用啦!
// 在需要使用的地方中调用
this.$openPreview(['http://...image-url.png'])