• 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默认组件中,加入以下代码:

    1. <script setup lang="ts">
    2. import {useRoute} from "vue-router";
    3. const route = useRoute()
    4. script>
    5. <template>
    6. <AConfigProvider>
    7. <AApp>
    8. <router-view/>
    9. AApp>
    10. AConfigProvider>
    11. template>
    12. <style scoped>
    13. .logo {
    14. height: 6em;
    15. padding: 1.5em;
    16. will-change: filter;
    17. transition: filter 300ms;
    18. }
    19. .logo:hover {
    20. filter: drop-shadow(0 0 2em #646cffaa);
    21. }
    22. .logo.vue:hover {
    23. filter: drop-shadow(0 0 2em #42b883aa);
    24. }
    25. style>

    使用Pinia Store封装全局引用
    1. import {App} from 'ant-design-vue';
    2. import type { MessageInstance } from 'ant-design-vue/es/message/interface';
    3. import type { ModalStaticFunctions } from 'ant-design-vue/es/modal/confirm';
    4. import type { NotificationInstance } from 'ant-design-vue/es/notification/interface';
    5. import {defineStore} from "pinia";
    6. export const useGloablStore = defineStore('global', () => {
    7. let message: MessageInstance = ref();
    8. let notification: NotificationInstance = ref();
    9. let modal: Omit<ModalStaticFunctions, 'warn'> = ref();
    10. (() => {
    11. const staticFunction = App.useApp();
    12. message = staticFunction.message;
    13. modal = staticFunction.modal;
    14. notification = staticFunction.notification;
    15. })();
    16. return { message, notification, modal };
    17. });
    在组件或者脚本中使用

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

    1. const { message, modal, notification } = useGloablStore()
    2. // 使用 message
    3. message.success('Success!');
    4. // 使用 modal
    5. modal.warning({
    6. title: 'This is a warning message',
    7. content: 'some messages...some messages...',
    8. });
    9. // 使用 notification
    10. notification.info({
    11. message: `Notification topLeft`,
    12. description: 'Hello, Ant Design Vue!!',
    13. placement: 'topLeft',
    14. });

    总结

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

  • 相关阅读:
    消息队列 RocketMQ 消息重复消费问题(原因及解决)
    Socket套接字编程
    常用设计模式
    9月9日,每日信息差
    C++面试常见问题多态如何实现?虚函数的底层如何实现?
    [模拟赛]2022.07.25
    Java - equals 与 == 的区别
    SQL注入测试
    Netty——NIO(Selector处理read事件)代码示例
    Vue.js 框架源码与进阶 - Vue.js 3.0 Vite 实现原理
  • 原文地址:https://blog.csdn.net/u010454030/article/details/133816050