<docs>
---
order: 13
title:
  zh-CN: 自定义渲染对话框
  en-US: Custom modal content render
---

## zh-CN

自定义渲染对话框, 可通过 `vueuse` 来实现拖拽。

## en-US

Custom modal content render. use `vueuse` implements draggable.

</docs>

<template>
  <div>
    <a-button type="primary" @click="showModal">Open Modal</a-button>
    <a-modal ref="modalRef" v-model:visible="visible" @ok="handleOk">
      <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p>
      <template #title>
        <div ref="modalTitleRef" style="width: 100%; cursor: move">Draggable Modal</div>
      </template>
      <template #modalRender="{ originVNode }">
        <div :style="transformStyle">
          <component :is="originVNode" />
        </div>
      </template>
    </a-modal>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, computed, CSSProperties, watch, watchEffect } from 'vue';
import { useDraggable } from '@vueuse/core';
export default defineComponent({
  setup() {
    const visible = ref<boolean>(false);
    const modalTitleRef = ref<HTMLElement>(null);
    const showModal = () => {
      visible.value = true;
    };
    const { x, y, isDragging } = useDraggable(modalTitleRef);
    const handleOk = (e: MouseEvent) => {
      console.log(e);
      visible.value = false;
    };
    const startX = ref<number>(0);
    const startY = ref<number>(0);
    const startUpdatePos = ref(false);
    const transformX = ref(0);
    const transformY = ref(0);
    const preTransformX = ref(0);
    const preTransformY = ref(0);
    let timeoutId;
    watch(isDragging, () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        if (isDragging.value) {
          startX.value = x.value;
          startY.value = y.value;
          preTransformX.value = transformX.value;
          preTransformY.value = transformY.value;
          startUpdatePos.value = true;
        } else {
          startUpdatePos.value = false;
        }
      });
    });

    watchEffect(() => {
      if (startUpdatePos.value) {
        transformX.value = preTransformX.value + x.value - startX.value;
        transformY.value = preTransformY.value + y.value - startY.value;
      }
    });
    const transformStyle = computed<CSSProperties>(() => {
      return {
        transform: `translate(${transformX.value}px, ${transformY.value}px)`,
      };
    });
    return {
      visible,
      showModal,
      handleOk,
      modalTitleRef,
      transformStyle,
    };
  },
});
</script>
