正文

vue3+ts+elementPLus实现v-preview指令(vue3.0写法)太疯狂了

文章摘要

这篇文章介绍了一个使用Vue框架和Element Plus组件构建的Vue组件,该组件通过槽绑定(Slots)实现了动态绑定图片源的功能。当组件实例化时,槽绑定会自动获取插槽中的imgSrc属性值,实现对图片源的动态更新。此外,组件还支持双击事件,双击时会调用el-dialog组件显示图片预览。组件还定义了expose API,提供了show和setSrc方法供外部调用,同时包含了关闭按钮逻辑,移除dom中已加载的图片元素。整个组件简洁明了,实现了图片预览和管理功能。

<template> ? ? <div class=”previewImg” @click=”dialogVisible=true”> ? ? ? ? <slot> ? ? ? ? ? ? <img :src=”https://www.jb51.net/article/props.src” alt=”图片加载失败” /> ? ? ? ? </slot> ? ? </div> ? ? <el-dialog v-model=”dialogVisible” title=”查看图片” @close=”close”> ? ? ? ? <img :src=”https://www.jb51.net/article/imgSrc” alt=”Preview Image” style=”max-width: 100%” /> ? ? </el-dialog> </template> <script setup lang=”ts”> ? ? import { ref, getCurrentInstance, ComponentInternalInstance, onMounted } from ‘vue’ ? ? import { ElDialog } from ‘element-plus’ ? ? const props=defineProps({ ? ? ? ? src: String ? ? }) ? ? const dialogVisible=ref(false) ? ? const imgSrc=ref(”) ? ? // 插槽形式 ? ? onMounted(()=> { ? ? ? ? const { proxy }=getCurrentInstance() as ComponentInternalInstance ? ? ? ? let slot=proxy?.$slots?.default?.() ? ? ? ? if(slot){ ? ? ? ? ? ? // 获取插槽内容设置imgSrc地址 ? ? ? ? ? ? imgSrc.value=slot?.[0]?.props?.src ? ? ? ? } ? ? }) ? ? const setSrc=(v: string)=> { ? ? ? ? imgSrc.value=v ? ? } ? ? // 组件触发 ? ? if (props.src) { ? ? ? ? setSrc(props.src) ? ? } ? ? // 指令触发 ? ? const show=()=> { ? ? ? ? dialogVisible.value=true ? ? } ? ? const close=()=> {? ? ? ? ? // 弹窗关闭移除dom ? ? ? ? if (document.getElementById(‘previewDom’)) { ? ? ? ? ? ? document.body.removeChild(document.getElementById(‘previewDom’) as HTMLElement) ? ? ? ? } ? ? } ? ? defineExpose({ ? ? ? ? show, ? ? ? ? setSrc ? ? }) </script>