Ant Design Vue 注册全局消息通知组件

前言

在一个前端工程中,消息通知组件都是使用频率非常高的组件,如果在 vue,jsx/tsx 的页面中直接使用是非常简单的,但有时候我们需要通过 API 的方式在 js 和 ts 这种非页面的场景中使用,比如 axios http 的全局拦截提示以及各种工具类的的封装中可能都会用到。

Ant Design Vue 官网文档中(Ant Design Vue — An enterprise-class UI components based on Ant Design and Vue.js)介绍通过 API 的方式使用 Message,Modal,Notification 三个组件并不详细,所以本文又整理了一下具体的使用步骤和方法。

使用

使用App包裹根组件

在App.vue默认组件中,加入以下代码:

<script setup lang="ts">
import {useRoute} from "vue-router";

const route = useRoute()



</script>

<template>

  <!-- ConfigProvider可以提供全局样式配置 -->
  <AConfigProvider> 
    <!-- A-APP是antd封装的组件,提供了消息通知组件的全局 project/inject -->
    <AApp> 
    <router-view/>
    </AApp>
  </AConfigProvider>

</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>

使用Pinia Store封装全局引用
import {App} from 'ant-design-vue';
import type { MessageInstance } from 'ant-design-vue/es/message/interface';
import type { ModalStaticFunctions } from 'ant-design-vue/es/modal/confirm';
import type { NotificationInstance } from 'ant-design-vue/es/notification/interface';
import {defineStore} from "pinia";


export const useGloablStore = defineStore('global', () => {
  let message: MessageInstance = ref();
  let notification: NotificationInstance = ref();
  let modal: Omit<ModalStaticFunctions, 'warn'> = ref();
  (() => {
    const staticFunction = App.useApp();
    message = staticFunction.message;
    modal = staticFunction.modal;
    notification = staticFunction.notification;
  })();

  return { message, notification, modal };
});
在组件或者脚本中使用

封装好了之后,在页面中或者 js 和 ts 脚本中使用,就像普通的 pinia store 一样,非常方便:


const { message, modal, notification } = useGloablStore()

// 使用 message
message.success('Success!');

// 使用 modal
modal.warning({
      title: 'This is a warning message',
      content: 'some messages...some messages...',
    });

// 使用 notification
notification.info({
      message: `Notification topLeft`,
      description: 'Hello, Ant Design Vue!!',
      placement: 'topLeft',
    });

总结

可以看到经过封装之后使用起来非常丝滑,只需要初始化一次,然后就可以在各个组件中使用,避免了将引用代码散落分散到各子组件中,提高了代码的简洁度和可维护性。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值