ant design for vue中的message如何在js、ts中使用?

错误方式1:采用provide、inject

//main.ts
import { message } from 'ant-design-vue'

app.provide('message', message);

//route/index.ts
import { MessageInstance } from "ant-design-vue/es/message";
import { message } from 'ant-design-vue'
router.beforeEach((to, from, next) => {
  const message: MessageInstance = inject('message') as MessageInstance;
  if (to.path == '/login') {
    next()
  } else {
    //其他逻辑
    message.info('登录过期,请重新登陆')
  }
})

在某些情况中控制台会报警告,无法注入。

错误方式2:app中挂载message

//main.ts
const app = createApp(App);
app.config.globalProperties.$message = message;

//request.ts
import {  getCurrentInstance } from 'vue';

client.interceptors.request.use((config: InternalAxiosRequestConfig<any>) => {
  const isToken = (config.headers || {}).isToken
  if (Cookies.get('accessToken') && isToken) {
    config.headers['Authorization'] = Cookies.get('accessToken')
  }
  return config;
}, (error) => {
  // 对请求错误做些什么
  const { proxy } = getCurrentInstance();
  //报错了………………
  return Promise.reject(error);
});

报错——getCurrentInstance is null

正确方式:

//App.vue
import { message } from 'ant-design-vue';
window.$message = message  //window上挂载

//ts申明window $message属性
declare global {
  interface Window {
    $message: MessageApi
  }
}

//任何地方
window.$message.success('')
window.$message.error('')