Modal 对话框

模态对话框。

何时使用

需要用户处理事务,又不希望跳转页面以致打断工作流程时,可以使用 Modal 在当前页面正中打开一个浮层,承载相应的操作。另外当需要一个简洁的确认框询问用户时,可以使用 Modal.confirm() 等语法糖方法。

代码演示

Modal 对话框 - 图1

异步关闭

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

  1. <template>
  2. <div>
  3. <a-button type="primary" @click="showModal">Open Modal with async logic</a-button>
  4. <a-modal
  5. title="Title"
  6. :visible="visible"
  7. @ok="handleOk"
  8. :confirmLoading="confirmLoading"
  9. @cancel="handleCancel"
  10. >
  11. <p>{{ModalText}}</p>
  12. </a-modal>
  13. </div>
  14. </template>
  15. <script>
  16. export default {
  17. data() {
  18. return {
  19. ModalText: 'Content of the modal',
  20. visible: false,
  21. confirmLoading: false,
  22. };
  23. },
  24. methods: {
  25. showModal() {
  26. this.visible = true;
  27. },
  28. handleOk(e) {
  29. this.ModalText = 'The modal will be closed after two seconds';
  30. this.confirmLoading = true;
  31. setTimeout(() => {
  32. this.visible = false;
  33. this.confirmLoading = false;
  34. }, 2000);
  35. },
  36. handleCancel(e) {
  37. console.log('Clicked cancel button');
  38. this.visible = false;
  39. },
  40. },
  41. };
  42. </script>

Modal 对话框 - 图2

基本

第一个对话框。

  1. <template>
  2. <div>
  3. <a-button type="primary" @click="showModal">Open Modal</a-button>
  4. <a-modal title="Basic Modal" v-model="visible" @ok="handleOk">
  5. <p>Some contents...</p>
  6. <p>Some contents...</p>
  7. <p>Some contents...</p>
  8. </a-modal>
  9. </div>
  10. </template>
  11. <script>
  12. export default {
  13. data() {
  14. return {
  15. visible: false,
  16. };
  17. },
  18. methods: {
  19. showModal() {
  20. this.visible = true;
  21. },
  22. handleOk(e) {
  23. console.log(e);
  24. this.visible = false;
  25. },
  26. },
  27. };
  28. </script>

Modal 对话框 - 图3

确认对话框(promise)

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

  1. <template>
  2. <a-button @click="showConfirm">
  3. Confirm
  4. </a-button>
  5. </template>
  6. <script>
  7. export default {
  8. methods: {
  9. showConfirm() {
  10. this.$confirm({
  11. title: 'Do you want to delete these items?',
  12. content: 'When clicked the OK button, this dialog will be closed after 1 second',
  13. onOk() {
  14. return new Promise((resolve, reject) => {
  15. setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
  16. }).catch(() => console.log('Oops errors!'));
  17. },
  18. onCancel() {},
  19. });
  20. },
  21. },
  22. };
  23. </script>

Modal 对话框 - 图4

确认对话框

使用 confirm() 可以快捷地弹出确认框。

  1. <template>
  2. <div>
  3. <a-button @click="showConfirm">
  4. Confirm
  5. </a-button>
  6. <a-button @click="showDeleteConfirm" type="dashed">
  7. Delete
  8. </a-button>
  9. <a-button @click="showPropsConfirm" type="dashed">
  10. With extra props
  11. </a-button>
  12. </div>
  13. </template>
  14. <script>
  15. export default {
  16. methods: {
  17. showConfirm() {
  18. this.$confirm({
  19. title: 'Do you Want to delete these items?',
  20. content: h => <div style="color:red;">Some descriptions</div>,
  21. onOk() {
  22. console.log('OK');
  23. },
  24. onCancel() {
  25. console.log('Cancel');
  26. },
  27. class: 'test',
  28. });
  29. },
  30. showDeleteConfirm() {
  31. this.$confirm({
  32. title: 'Are you sure delete this task?',
  33. content: 'Some descriptions',
  34. okText: 'Yes',
  35. okType: 'danger',
  36. cancelText: 'No',
  37. onOk() {
  38. console.log('OK');
  39. },
  40. onCancel() {
  41. console.log('Cancel');
  42. },
  43. });
  44. },
  45. showPropsConfirm() {
  46. this.$confirm({
  47. title: 'Are you sure delete this task?',
  48. content: 'Some descriptions',
  49. okText: 'Yes',
  50. okType: 'danger',
  51. okButtonProps: {
  52. props: { disabled: true },
  53. },
  54. cancelText: 'No',
  55. onOk() {
  56. console.log('OK');
  57. },
  58. onCancel() {
  59. console.log('Cancel');
  60. },
  61. });
  62. },
  63. },
  64. };
  65. </script>

Modal 对话框 - 图5

自定义页脚

更复杂的例子,自定义了页脚的按钮,点击提交后进入 loading 状态,完成后关闭。不需要默认确定取消按钮时,你可以把 footer 设为 null

  1. <template>
  2. <div>
  3. <a-button type="primary" @click="showModal">
  4. Open Modal with customized footer
  5. </a-button>
  6. <a-modal v-model="visible" title="Title" onOk="handleOk">
  7. <template slot="footer">
  8. <a-button key="back" @click="handleCancel">Return</a-button>
  9. <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
  10. Submit
  11. </a-button>
  12. </template>
  13. <p>Some contents...</p>
  14. <p>Some contents...</p>
  15. <p>Some contents...</p>
  16. <p>Some contents...</p>
  17. <p>Some contents...</p>
  18. </a-modal>
  19. </div>
  20. </template>
  21. <script>
  22. export default {
  23. data() {
  24. return {
  25. loading: false,
  26. visible: false,
  27. };
  28. },
  29. methods: {
  30. showModal() {
  31. this.visible = true;
  32. },
  33. handleOk(e) {
  34. this.loading = true;
  35. setTimeout(() => {
  36. this.visible = false;
  37. this.loading = false;
  38. }, 3000);
  39. },
  40. handleCancel(e) {
  41. this.visible = false;
  42. },
  43. },
  44. };
  45. </script>

Modal 对话框 - 图6

信息提示

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

  1. <template>
  2. <div>
  3. <a-button @click="info">Info</a-button>
  4. <a-button @click="success">Success</a-button>
  5. <a-button @click="error">Error</a-button>
  6. <a-button @click="warning">Warning</a-button>
  7. </div>
  8. </template>
  9. <script>
  10. import { Modal } from 'ant-design-vue';
  11. export default {
  12. methods: {
  13. info() {
  14. const h = this.$createElement;
  15. this.$info({
  16. title: 'This is a notification message',
  17. content: h('div', {}, [
  18. h('p', 'some messages...some messages...'),
  19. h('p', 'some messages...some messages...'),
  20. ]),
  21. onOk() {},
  22. });
  23. },
  24. success() {
  25. this.$success({
  26. title: 'This is a success message',
  27. // JSX support
  28. content: (
  29. <div>
  30. <p>some messages...some messages...</p>
  31. <p>some messages...some messages...</p>
  32. </div>
  33. ),
  34. });
  35. },
  36. error() {
  37. this.$error({
  38. title: 'This is an error message',
  39. content: 'some messages...some messages...',
  40. });
  41. },
  42. warning() {
  43. this.$warning({
  44. title: 'This is a warning message',
  45. content: 'some messages...some messages...',
  46. });
  47. },
  48. },
  49. };
  50. </script>

Modal 对话框 - 图7

国际化

设置 okTextcancelText 以自定义按钮文字。

  1. <template>
  2. <div>
  3. <a-button type="primary" @click="showModal">Modal</a-button>
  4. <a-modal title="Modal" v-model="visible" @ok="hideModal" okText="确认" cancelText="取消">
  5. <p>Bla bla ...</p>
  6. <p>Bla bla ...</p>
  7. <p>Bla bla ...</p>
  8. </a-modal>
  9. <br />
  10. <br />
  11. <a-button @click="confirm">Confirm</a-button>
  12. </div>
  13. </template>
  14. <script>
  15. export default {
  16. data() {
  17. return {
  18. visible: false,
  19. };
  20. },
  21. methods: {
  22. showModal() {
  23. this.visible = true;
  24. },
  25. hideModal() {
  26. this.visible = false;
  27. },
  28. confirm() {
  29. this.$confirm({
  30. title: 'Confirm',
  31. content: 'Bla bla ...',
  32. okText: '确认',
  33. cancelText: '取消',
  34. });
  35. },
  36. },
  37. };
  38. </script>

Modal 对话框 - 图8

手动更新和移除

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

<template>
  <a-button @click="countDown">Open modal to close in 5s</a-button>
</template>
<script>
  export default {
    methods: {
      countDown() {
        let secondsToGo = 5;
        const modal = this.$success({
          title: 'This is a notification message',
          content: `This modal will be destroyed after ${secondsToGo} second.`,
        });
        const interval = setInterval(() => {
          secondsToGo -= 1;
          modal.update({
            content: `This modal will be destroyed after ${secondsToGo} second.`,
          });
        }, 1000);
        setTimeout(() => {
          clearInterval(interval);
          modal.destroy();
        }, secondsToGo * 1000);
      },
    },
  };
</script>

Modal 对话框 - 图9

自定义位置

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

<template>
  <div id="components-modal-demo-position">
    <a-button type="primary" @click="() => setModal1Visible(true)"
      >Display a modal dialog at 20px to Top</a-button
    >
    <a-modal
      title="20px to Top"
      style="top: 20px;"
      :visible="modal1Visible"
      @ok="() => setModal1Visible(false)"
      @cancel="() => setModal1Visible(false)"
    >
      <p>some contents...</p>
      <p>some contents...</p>
      <p>some contents...</p>
    </a-modal>
    <br /><br />
    <a-button type="primary" @click="() => modal2Visible = true"
      >Vertically centered modal dialog</a-button
    >
    <a-modal
      title="Vertically centered modal dialog"
      centered
      v-model="modal2Visible"
      @ok="() => modal2Visible = false"
    >
      <p>some contents...</p>
      <p>some contents...</p>
      <p>some contents...</p>
    </a-modal>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        modal1Visible: false,
        modal2Visible: false,
      };
    },
    methods: {
      setModal1Visible(modal1Visible) {
        this.modal1Visible = modal1Visible;
      },
    },
  };
</script>

Modal 对话框 - 图10

自定义页脚按钮属性

传入 okButtonPropscancelButtonProps 可分别自定义确定按钮和取消按钮的 props。

<template>
  <div>
    <a-button type="primary" @click="showModal">Open Modal with customized button props</a-button>
    <a-modal
      title="Basic Modal"
      v-model="visible"
      @ok="handleOk"
      :okButtonProps="{ props: {disabled: true} }"
      :cancelButtonProps="{ props: {disabled: true} }"
    >
      <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p>
    </a-modal>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        visible: false,
      };
    },
    methods: {
      showModal() {
        this.visible = true;
      },
      handleOk(e) {
        console.log(e);
        this.visible = false;
      },
      handleCancel(e) {
        console.log(e);
        this.visible = false;
      },
    },
  };
</script>

Modal 对话框 - 图11

销毁确认对话框

使用 Modal.destroyAll() 可以销毁弹出的确认窗。通常用于路由监听当中,处理路由前进、后退不能销毁确认对话框的问题。

<template>
  <a-button @click="showConfirm">
    Confirm
  </a-button>
</template>
<script>
  import Button from '../../button';
  export default {
    methods: {
      showConfirm() {
        const self = this;
        for (let i = 0; i < 3; i += 1) {
          setTimeout(() => {
            this.$confirm({
              content: 'destroy all',
              onOk() {
                return new Promise((resolve, reject) => {
                  setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                }).catch(() => console.log('Oops errors!'));
              },
              cancelText: 'Click to destroy all',
              onCancel() {
                self.destroyAll();
              },
            });
          }, i * 500);
        }
      },
      destroyAll() {
        this.$destroyAll();
      },
    },
  };
</script>

API

参数说明类型默认值
afterCloseModal 完全关闭后的回调function
bodyStyleModal body 样式object{}
cancelText取消按钮文字string| slot取消
centered垂直居中展示 ModalBooleanfalse
closable是否显示右上角的关闭按钮booleantrue
confirmLoading确定按钮 loadingboolean
destroyOnClose关闭时销毁 Modal 里的子元素booleanfalse
footer底部内容,当不需要默认底部按钮时,可以设为 :footer="null"string|slot确定取消按钮
forceRender强制渲染 Modalbooleanfalse
getContainer指定 Modal 挂载的 HTML 节点(instance): HTMLElement() => document.body
keyboard是否支持键盘 esc 关闭booleantrue
mask是否展示遮罩Booleantrue
maskClosable点击蒙层是否允许关闭booleantrue
maskStyle遮罩样式object{}
okText确认按钮文字string|slot确定
okType确认按钮类型stringprimary
okButtonPropsok 按钮 props, 遵循 jsx规范{props: ButtonProps, on: {}}-
cancelButtonPropscancel 按钮 props, 遵循 jsx规范{props: ButtonProps, on: {}}-
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.method()

包括:

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

以上均为一个函数,参数为 object,具体属性如下:

参数说明类型默认值
autoFocusButton指定自动获得焦点的按钮null|string: ok cancelok
cancelText取消按钮文字string取消
centered垂直居中展示 ModalBooleanfalse
closable是否显示右上角的关闭按钮booleanfalse
class容器类名string-
content内容string |vNode |function(h)
icon自定义图标(1.14.0 新增)string|()=>VNode<Icon type="question-circle">
iconType图标类型(1.14.0 后废弃,请使用 iconstringquestion-circle
mask是否展示遮罩Booleantrue
maskClosable点击蒙层是否允许关闭Booleanfalse
keyboard是否支持键盘 esc 关闭booleantrue
okText确认按钮文字string确定
okType确认按钮类型stringprimary
okButtonPropsok 按钮 propsButtonProps-
cancelButtonPropscancel 按钮 propsButtonProps-
title标题string|vNode |function(h)
width宽度string|number416
zIndex设置 Modal 的 z-indexNumber1000
onCancel取消回调,参数为关闭函数,返回 promise 时 resolve 后自动关闭function
onOk点击确定回调,参数为关闭函数,返回 promise 时 resolve 后自动关闭function

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

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() 适用于主动关闭,而不是路由这样被动关闭)

const router = new VueRouter({ ... })

// router change
router.beforeEach((to, from, next) => {
  Modal.destroyAll();
})