前言
在一个前端工程中,消息通知组件都是使用频率非常高的组件,如果在 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',
});
总结
可以看到经过封装之后使用起来非常丝滑,只需要初始化一次,然后就可以在各个组件中使用,避免了将引用代码散落分散到各子组件中,提高了代码的简洁度和可维护性。