Skip to content

Modal 对话框

模态对话框。

何时使用

需要用户处理事务,又不希望跳转页面以致打断工作流程时,可以使用 Modal 在当前页面正中打开一个浮层,承载相应的操作。

另外当需要一个简洁的确认框询问用户时,可以使用 Modal.confirm() 等语法糖方法。

基本用法

第一个对话框。

vue
<template>
  <div>
    <g-button type="primary" @click="showModal">Open Modal</g-button>
    <g-modal
      v-model:visible="visible"
      title="Basic Modal"
      @ok="handleOk"
    >
      <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p>
    </g-modal>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const visible = ref(false)
    
    const showModal = () => {
      visible.value = true
    }
    
    const handleOk = (e) => {
      console.log(e)
      visible.value = false
    }
    
    return {
      visible,
      showModal,
      handleOk
    }
  }
}
</script>

异步关闭

点击确定后异步关闭对话框,例如提交表单。

vue
<template>
  <div>
    <g-button type="primary" @click="showModal">Open Modal with async logic</g-button>
    <g-modal
      v-model:visible="visible"
      title="Title"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <p>{{ modalText }}</p>
    </g-modal>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const visible = ref(false)
    const confirmLoading = ref(false)
    const modalText = ref('Content of the modal')
    
    const showModal = () => {
      visible.value = true
    }
    
    const handleOk = () => {
      modalText.value = 'The modal will be closed after two seconds'
      confirmLoading.value = true
      setTimeout(() => {
        visible.value = false
        confirmLoading.value = false
      }, 2000)
    }
    
    const handleCancel = () => {
      console.log('Clicked cancel button')
      visible.value = false
    }
    
    return {
      visible,
      confirmLoading,
      modalText,
      showModal,
      handleOk,
      handleCancel
    }
  }
}
</script>

自定义页脚

更复杂的例子,自定义了页脚的按钮,点击提交后进入 loading 状态,完成后关闭。

不需要默认确定取消按钮时,你可以把 footer 设为 null

vue
<template>
  <div>
    <g-button type="primary" @click="showModal">Open Modal with customized footer</g-button>
    <g-modal
      v-model:visible="visible"
      title="Title"
      @cancel="handleCancel"
    >
      <template #footer>
        <g-button key="back" @click="handleCancel">Return</g-button>
        <g-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleOk"
        >
          Submit
        </g-button>
      </template>
      <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p>
    </g-modal>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const visible = ref(false)
    const loading = ref(false)
    
    const showModal = () => {
      visible.value = true
    }
    
    const handleOk = () => {
      loading.value = true
      setTimeout(() => {
        loading.value = false
        visible.value = false
      }, 3000)
    }
    
    const handleCancel = () => {
      visible.value = false
    }
    
    return {
      visible,
      loading,
      showModal,
      handleOk,
      handleCancel
    }
  }
}
</script>

确认对话框

使用 confirm() 可以快捷地弹出确认框。onCancel/onOk 返回 promise 可以延迟关闭。

vue
<template>
  <div>
    <g-button @click="showConfirm">Confirm</g-button>
    <g-button @click="showPromiseConfirm" type="dashed">
      With promise
    </g-button>
    <g-button @click="showDeleteConfirm" type="dashed">
      Delete
    </g-button>
    <g-button @click="showPropsConfirm" type="dashed">
      With extra props
    </g-button>
  </div>
</template>

<script>
import { Modal } from '@/components'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'

export default {
  setup() {
    const showConfirm = () => {
      Modal.confirm({
        title: 'Do you Want to delete these items?',
        icon: createVNode(ExclamationCircleOutlined),
        content: 'Some descriptions',
        onOk() {
          console.log('OK')
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    }
    
    const showPromiseConfirm = () => {
      Modal.confirm({
        title: 'Do you want to delete these items?',
        icon: createVNode(ExclamationCircleOutlined),
        content: 'When clicked the OK button, this dialog will be closed after 1 second',
        onOk() {
          return new Promise((resolve, reject) => {
            setTimeout(Math.random() > 0.5 ? resolve : reject, 1000)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {},
      })
    }
    
    const showDeleteConfirm = () => {
      Modal.confirm({
        title: 'Are you sure delete this task?',
        icon: createVNode(ExclamationCircleOutlined),
        content: 'Some descriptions',
        okText: 'Yes',
        okType: 'danger',
        cancelText: 'No',
        onOk() {
          console.log('OK')
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    }
    
    const showPropsConfirm = () => {
      Modal.confirm({
        title: 'Are you sure delete this task?',
        icon: createVNode(ExclamationCircleOutlined),
        content: 'Some descriptions',
        okText: 'Yes',
        okType: 'danger',
        okButtonProps: {
          disabled: true,
        },
        cancelText: 'No',
        onOk() {
          console.log('OK')
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    }
    
    return {
      showConfirm,
      showPromiseConfirm,
      showDeleteConfirm,
      showPropsConfirm
    }
  }
}
</script>

信息提示

各种类型的信息提示,只提供一个按钮用于关闭。

vue
<template>
  <div>
    <g-button @click="info">Info</g-button>
    <g-button @click="success">Success</g-button>
    <g-button @click="error">Error</g-button>
    <g-button @click="warning">Warning</g-button>
  </div>
</template>

<script>
import { Modal } from '@/components'
import { createVNode } from 'vue'
import {
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  InfoCircleOutlined
} from '@ant-design/icons-vue'

export default {
  setup() {
    const info = () => {
      Modal.info({
        title: 'This is a notification message',
        icon: createVNode(InfoCircleOutlined),
        content: 'some messages...some messages...',
        onOk() {},
      })
    }
    
    const success = () => {
      Modal.success({
        title: 'This is a success message',
        icon: createVNode(CheckCircleOutlined),
        content: 'some messages...some messages...',
      })
    }
    
    const error = () => {
      Modal.error({
        title: 'This is an error message',
        icon: createVNode(CloseCircleOutlined),
        content: 'some messages...some messages...',
      })
    }
    
    const warning = () => {
      Modal.warning({
        title: 'This is a warning message',
        icon: createVNode(ExclamationCircleOutlined),
        content: 'some messages...some messages...',
      })
    }
    
    return {
      info,
      success,
      error,
      warning
    }
  }
}
</script>

手动更新和移除

手动更新和关闭 Modal.method 方式创建的对话框。

vue
<template>
  <div>
    <g-button @click="countDown">Open modal to close in 5s</g-button>
  </div>
</template>

<script>
import { Modal } from '@/components'

export default {
  setup() {
    const countDown = () => {
      let secondsToGo = 5
      const modal = Modal.success({
        title: 'This is a notification message',
        content: `This modal will be destroyed after ${secondsToGo} second.`,
      })
      
      const timer = setInterval(() => {
        secondsToGo -= 1
        modal.update({
          content: `This modal will be destroyed after ${secondsToGo} second.`,
        })
      }, 1000)
      
      setTimeout(() => {
        clearInterval(timer)
        modal.destroy()
      }, secondsToGo * 1000)
    }
    
    return {
      countDown
    }
  }
}
</script>

自定义位置

使用 centered 或类似 style.top 的样式来设置对话框位置。

vue
<template>
  <div>
    <g-button type="primary" @click="setModal1Visible(true)">
      Display a modal dialog at 20px to Top
    </g-button>
    <g-modal
      title="20px to Top"
      :style="{ top: '20px' }"
      v-model:visible="modal1Visible"
      @ok="() => setModal1Visible(false)"
    >
      <p>some contents...</p>
      <p>some contents...</p>
      <p>some contents...</p>
    </g-modal>
    
    <br /><br />
    <g-button type="primary" @click="setModal2Visible(true)">
      Vertically centered modal dialog
    </g-button>
    <g-modal
      title="Vertically centered modal dialog"
      centered
      v-model:visible="modal2Visible"
      @ok="() => setModal2Visible(false)"
    >
      <p>some contents...</p>
      <p>some contents...</p>
      <p>some contents...</p>
    </g-modal>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const modal1Visible = ref(false)
    const modal2Visible = ref(false)
    
    const setModal1Visible = (visible) => {
      modal1Visible.value = visible
    }
    
    const setModal2Visible = (visible) => {
      modal2Visible.value = visible
    }
    
    return {
      modal1Visible,
      modal2Visible,
      setModal1Visible,
      setModal2Visible
    }
  }
}
</script>

自定义模态的宽度

使用 width 来设置模态对话框的宽度。

vue
<template>
  <div>
    <g-button type="primary" @click="setModalVisible(true)">
      Open Modal of 1000px width
    </g-button>
    <g-modal
      title="Modal 1000px width"
      centered
      v-model:visible="modalVisible"
      @ok="() => setModalVisible(false)"
      width="1000px"
    >
      <p>some contents...</p>
      <p>some contents...</p>
      <p>some contents...</p>
    </g-modal>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const modalVisible = ref(false)
    
    const setModalVisible = (visible) => {
      modalVisible.value = visible
    }
    
    return {
      modalVisible,
      setModalVisible
    }
  }
}
</script>

API

参数说明类型默认值版本
afterCloseModal 完全关闭后的回调function-
bodyStyleModal body 样式object{}
cancelButtonPropscancel 按钮 propsButtonProps-
cancelText取消按钮文字string | slot取消
centered垂直居中展示 Modalbooleanfalse
closable是否显示右上角的关闭按钮booleantrue
closeIcon自定义关闭图标VNode | slot-
confirmLoading确定按钮 loadingbooleanfalse
destroyOnClose关闭时销毁 Modal 里的子元素booleanfalse
dialogClass可用于设置浮层的类名string-
dialogStyle可用于设置浮层的样式,调整浮层位置等object-
footer底部内容,当不需要默认底部按钮时,可以设为 :footer="null"string | slot确定取消按钮
forceRender强制渲染 Modalbooleanfalse
getContainer指定 Modal 挂载的 HTML 节点, false 为挂载在当前 domHTMLElement | () => HTMLElement | Selectors | falsedocument.body
keyboard是否支持键盘 esc 关闭booleantrue
mask是否展示遮罩booleantrue
maskClosable点击蒙层是否允许关闭booleantrue
maskStyle遮罩样式object{}
okButtonPropsok 按钮 propsButtonProps-
okText确认按钮文字string | slot确定
okType确认按钮类型stringprimary
title标题string | slot-
visible(v-model)对话框是否可见boolean-
width宽度string | number520
wrapClassName对话框外层容器的类名string-
zIndex设置 Modal 的 z-indexnumber1000

事件

事件名称说明回调参数
cancel点击遮罩层或右上角叉或取消按钮的回调function(e)
ok点击确定回调function(e)

注意

<Modal /> 默认关闭后状态不会自动清空, 如果希望每次打开都是新内容,请设置 destroyOnClose

包括:

  • Modal.info
  • Modal.success
  • Modal.error
  • Modal.warning
  • Modal.confirm

以上均为一次性方法,调用后即会被销毁。本例中的 config 参数如下:

参数说明类型默认值版本
autoFocusButton指定自动获得焦点的按钮null | string: ok | cancelok
cancelButtonPropscancel 按钮 propsButtonProps-
cancelText设置 Modal.confirm 取消按钮文字string取消
centered垂直居中展示 Modalbooleanfalse
class容器类名string-
closable是否显示右上角的关闭按钮booleanfalse
content内容string | VNode | function(h)-
icon自定义图标VNode | () => VNode-
keyboard是否支持键盘 esc 关闭booleantrue
mask是否展示遮罩booleantrue
maskClosable点击蒙层是否允许关闭booleanfalse
okButtonPropsok 按钮 propsButtonProps-
okText确认按钮文字string确定
okType确认按钮类型stringprimary
style可用于设置浮层的样式,调整浮层位置等CSSProperties-
title标题string | VNode | function(h)-
width宽度string | number416
zIndex设置 Modal 的 z-indexnumber1000
onCancel取消回调,参数为关闭函数,返回 promise 时 resolve 后自动关闭function(close)-
onOk点击确定回调,参数为关闭函数,返回 promise 时 resolve 后自动关闭function(close)-

以上函数调用后,会返回一个引用,可以通过该引用更新和关闭弹窗。

js
const modal = Modal.info();

modal.update({
  title: '修改的标题',
  content: '修改的内容',
});

modal.destroy();
  • Modal.destroyAll

使用 Modal.destroyAll() 可以销毁弹出的确认窗(即上述的 Modal.info、Modal.success、Modal.error、Modal.warning、Modal.confirm)。通常用于路由监听当中,处理路由前进、后退不能销毁确认对话框的问题,而不用各处去使用实例的返回值进行关闭(modal.destroy() 适用于主动关闭,而不是路由这样被动关闭)

js
import { watch } from 'vue';
import { Modal } from 'ant-design-vue';

watch(router.currentRoute, () => {
  Modal.destroyAll();
});

当你需要使用 Context 时,可以通过 Modal.useModal 创建一个 contextHolder 插入子节点中。通过 hooks 创建的临时 Modal 将会得到 contextHolder 所在位置的所有上下文。创建的 modal 对象拥有与 [Modal.method] 相同的创建通知方法。

vue
<template>
  <div>
    <contextHolder />
    <!-- your components -->
  </div>
</template>

<script>
import { Modal } from '@/components'

export default {
  setup() {
    const [modal, contextHolder] = Modal.useModal()
    
    const info = () => {
      modal.info({
        title: 'Useful information',
        content: 'some useful information',
      })
    }
    
    return {
      contextHolder,
      info
    }
  }
}
</script>

FAQ

为什么 Modal 方法不能获取 context、redux、的内容和 ConfigProvider locale/prefixCls/theme 等配置?

直接调用 Modal 方法,antdv 会通过 Vue.render 动态创建新的 Vue 实体。其 context 与当前代码所在 context 并不相同,因而无法获取 context 信息。

当你需要 context 信息(例如 ConfigProvider 配置)时,可以通过 Modal.useModal 方法会返回 api 实体以及 contextHolder 节点。将其插入到你需要获取 context 位置即可:

vue
<template>
  <div>
    <contextHolder />
    <!-- your components -->
  </div>
</template>

<script>
import { Modal } from '@/components'

export default {
  setup() {
    const [api, contextHolder] = Modal.useModal()
    
    const info = () => {
      api.info({
        // ...
      })
    }
    
    return {
      contextHolder,
      info
    }
  }
}
</script>

异同:通过 hooks 创建的 contextHolder 必须插入到子元素节点中才会生效,当你不需要上下文信息时请直接调用。

可通过 App 包裹组件 简化 useModal 等方法需要手动植入 contextHolder 的问题。

Released under the MIT License.