Vue3封装函数组件(ElImageViewer)预览图片

2023-07-31 11:00:23 浏览数 (1)

目录结构

index.vue

代码语言:javascript复制
<template>
    <el-image-viewer v-if="show" v-bind="$attrs" hide-on-click-modal @close="show = false" />
</template>
 
<script setup>
import { ref, watch } from "vue"
import { ElImageViewer } from "element-plus" //自定义函数组件无法使用全局组件,需要单独引入

const props = defineProps({
    visible: {
        type: Boolean,
        default: false,
    },
    remove: {
        type: Function, //传入createApp中移除节点的方法
        default: null,
    },
    // api文档:https://element-plus.org/zh-CN/component/image.html#image-viewer-attributes
})

const show = ref(props.visible)
// 监听显示的消失,需要移除dom
watch(() => show.value, (val) => {
    !val && props.remove()
})
</script>

index.js

代码语言:javascript复制
import { createApp } from 'vue'
import index from './index.vue'

export default (options) => {
    // 创建一个节点,并将组件挂载上去
    const root = document.createElement('div')
    document.body.appendChild(root)

    const app = createApp(index, {
        ...options, visible: true, remove() {
            app.unmount(root) //创建完后要进行销毁
            document.body.removeChild(root)
        }
    })
    return app.mount(root)
}

使用方法在js||vue文件中

代码语言:javascript复制
import previewImage from "@/fcComponents/previewImage"
previewImage({ urlList: ["https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg"] })

0 人点赞