Skip to content
On this page

Message 消息提示

常用于主动操作后的反馈提示。

基础用法

从顶部出现,3 秒后自动消失。 注册了一个 createMessage 方法用于调用。 Message 可以接收一个字符串或一个 VNode 作为参数,它会被显示为正文内容。

<script setup>
import { h } from 'vue'
import { createMessage } from '@/components/Message/method'
import Button from '@/components/Button/Button.vue'
const open = () => {
  createMessage({ message: 'hello world' })
}
const open2 = () => {
  createMessage({ message: h('b', 'this is bold') })
}
</script>
<template>
<div class="basic block">
  <Button type="primary" @click="open"> 创建一条消息 </Button>
  <Button  @click="open2"> 创建支持 VNode 的消息 </Button>
</div>
</template>

不同状态

用来显示「成功、警告、消息、错误」类的操作反馈。设置 type 字段可以定义不同的状态,默认为info。

<script setup>
import { createMessage } from '@/components/Message/method'
import Button from '@/components/Button/Button.vue'
const open = (type) => {
  createMessage({ message: 'hello world', type })
}
</script>
<template>
<div class="basic block">
  <Button @click="open('success')"> Success </Button>
  <Button @click="open('info')"> Info </Button>
  <Button @click="open('warning')"> warning </Button>
  <Button @click="open('danger')"> Danger </Button>
</div>
</template>

可关闭的消息提示

可以添加关闭按钮。

默认的 Message 是不可以被人工关闭的。 如果你需要手动关闭功能,你可以把 showClose 设置为 true ,Message 拥有可控的 duration, 默认的关闭时间为 3000 毫秒,当把这个属性的值设置为0便表示该消息不会被自动关闭。

<script setup>
import { createMessage } from '@/components/Message/method'
import Button from '@/components/Button/Button.vue'
const open = () => {
  createMessage({ message: 'hello world', showClose: true, duration: 0 })
}
</script>
<template>
<div class="basic block">
  <Button @click="open"> 可关闭消息 </Button>
</div>
</template>

手动关闭所有实例

可以调用 message 模块提供了一个 closeAll() 手动关闭所有实例。

<script setup>
import { createMessage, closeAll } from '@/components/Message/method'
import Button from '@/components/Button/Button.vue'
const open = () => {
  createMessage({ message: 'hello world1', duration: 0 })
  createMessage({ message: 'hello world2', duration: 0 })
  createMessage({ message: 'hello world3', duration: 0 })
}
const close = () => {
  closeAll()
}
</script>
<template>
<div class="basic block">
  <Button @click="open"> 创建三条消息 </Button>
  <Button @click="close"> 全部关闭 </Button>
</div>
</template>

API

Message 配置项

使用 createMessage 创建信息,它接受一个Object,以下是 Object 中的属性列表。

NameDescriptionTypeDefault
message消息文字'string' | 'vNode'
type消息类型'success' | 'warning' |'info' | 'danger'info
showClose是否显示关闭按钮booleanfalse
duration显示时间,单位为毫秒。 设为 0 则不会自动关闭number3000

Message 方法

调用 createMessage 会返回当前 Message 的实例。 如果需要手动关闭实例,可以调用它的 close 方法。

NameDescriptionType
close关闭当前的 Message() => void

全局方法

调用 message 模块提供了的一个 closeAll() 方法可以手动关闭所有实例。

NameDescriptionType
closeAll关闭当前所有的 Message() => void