Vue3 配合 Element-Plus 和 iframe-resizer 完美实现抽屉 Drawer 和 iframe

环境准备

pnpm install vue lodash element-plus iframe-resizer
pnpm install @types/iframe-resizer -D

iframe

新建文件 src/utils/directives/iframeResize.ts

import { Directive, DirectiveBinding, nextTick } from "vue"
import iframeResize from "iframe-resizer/js/iframeResizer"
import { isDev } from "~/src/utils/constants.ts"
import _ from "lodash"

interface ResizableHTMLElement extends HTMLElement {
  iFrameResizer?: {
    removeListeners: () => void
  }
}

const resize: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const options = binding.value || {
      log: isDev,
      checkOrigin: false,
      iframeResizerEnable: true,
      autoResize: false,
      warningTimeout: 30000,
    }

    el.addEventListener("load", () => {
      nextTick(() => {
        // 获取最大宽度
        const maxWidth = _.max([
          document.body.offsetWidth,
          document.body.scrollWidth,
          document.documentElement.offsetWidth,
          document.documentElement.scrollWidth,
        ])

        // 设置元素高度为最大宽度
        el.style.height = maxWidth + "px"
        iframeResize(options, el)
      })
    })
  },
  unmounted(el: HTMLElement) {
    const resizableEl = el as ResizableHTMLElement

    if (resizableEl.iFrameResizer) {
      resizableEl.iFrameResizer.removeListeners()
    }
  },
}

export default resize

使用

抽屉占位

  <!-- 抽屉占位 -->
    <el-drawer v-model="showDrawer" size="85%" direction="rtl" :destroy-on-close="true">
      <DrawerBoxBridge :src="drawerSrc" />
    </el-drawer>

iframe

<!--suppress ALL -->
<script setup lang="ts">
const props = defineProps({
  src: {
    type: String,
    default: "",
  },
})
</script>

<template>
  <div>
    <iframe v-resize width="100%" :src="src" frameborder="0"></iframe>
  </div>
</template>

页面使用

const showDrawer = ref(false)
const drawerSrc = ref("")

const handleQuick = (index: number, row: any) => {
  const pageId = row.postid
  drawerSrc.value = `/#/publish/singlePublish/?id=${pageId}`
  showDrawer.value = true
}

大功告成。

效果预览

image

posted @ 2024-02-28 14:47  灯塔下的守望者  阅读(139)  评论(0编辑  收藏  举报