ant design vue中的全局提示(message)在js、ts中使用

本文分析了在Vue应用中使用AntDesignVuemessage组件时的错误用法,包括provide/inject和在app中挂载message,以及正确的全局挂载方式。重点介绍了如何避免console警告和在非Vue组件中访问message实例的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误方式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('')

### 使用 Ant Design Vue 实现图片上传 为了在 Vue 项目中利用 Ant Design Vue 组件库实现图片上传功能,需遵循特定配置流程并编写相应代码。 #### 安装依赖包 首先,在项目根目录执行命令安装 `ant-design-vue` 及其相关依赖项。这一步骤确保开发环境具备所需资源来加载和渲染 Ant Design 的组件[^2]。 ```bash npm install ant-design-vue --save ``` #### 配置全局引入 接着,在项目的入口文件 `main.js` 中按如下方式依次导入整个组件库及其默认样式: ```javascript import { createApp } from 'vue'; import App from './App.vue'; // 引入组件库 import antd from 'ant-design-vue'; // 引入样式表 import 'ant-design-vue/dist/antd.css'; const app = createApp(App); app.use(antd); // 注册所有组件 app.mount('#app'); ``` #### 创建上传组件实例 定义一个新的单文件组件用于处理具体的上传逻辑。此部分展示了如何设置 `<a-upload>` 标签属性以及关联事件处理器函数,从而构建一个简易却实用的图像上传界面[^5]。 ```html <template> <div id="uploader"> <!-- 图片卡片形式展示 --> <a-upload name="avatar" listType="picture-card" class="img-upload" :multiple="false" :beforeUpload="handleBeforeUpload" :customRequest="handleCustomRequest" :fileList="imageFiles" @preview="handlePreview" @change="handleChange" @remove="handleRemove" > <div v-if="imageFiles.length < 1"> <a-icon type="plus"/> <div>点击上传</div> </div> </a-upload> <!-- 查看大图模态框 --> <a-modal :visible="modalVisible" footer="" @cancel="closeModal"> <img alt="预览" style="width: 100%" :src="currentImageUrl"/> </a-modal> </div> </template> <script lang="ts"> export default { data() { return { imageFiles: [], // 存储已选中的文件列表 modalVisible: false, // 控制查看器显示状态 currentImageUrl: '', // 当前正在查看的大图链接 }; }, methods: { handleBeforeUpload(file) { const isValidFileType = file.type.startsWith('image/'); if (!isValidFileType) { this.$message.error(`${file.name} 文件类型不合法`); return false; } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { this.$message.error(`图片 ${file.name} 太大 (超过2MB)!`); return false; } return true; }, async handleCustomRequest(option) { try { let formData = new FormData(); formData.append('file', option.file); await fetch('/api/upload', { method: 'POST', body: formData, }); option.onSuccess?.(); // 成功回调 } catch(error){ console.log(error); option.onError?.(); // 错误回调 } }, handleChange(info) { switch (info.file.status) { case 'uploading': break; case 'done': this.imageFiles.push({...info.file}); break; case 'error': this.$message.error(`${info.file.name} 上传失败.`); break; } }, handlePreview(file) { this.currentImageUrl = file.url || file.thumbUrl; this.modalVisible = true; }, closeModel() { this.modalVisible = false; }, handleRemove(file) { this.imageFiles = this.imageFiles.filter(item => item.uid !== file.uid); } } }; </script> <style scoped> /* 自定义样式 */ .img-upload .ant-upload-select-picture-card i { font-size: 32px; color: #999; } .img-upload .ant-upload-select-picture-card div { margin-top: 8px; color: #666; } </style> ``` 上述代码片段实现了基本的图片上传功能,并提供了简单的前端验证机制以保证用户体验流畅性。同时,通过自定义请求方法可以灵活对接不同的后端接口完成实际的数据传输操作[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你熬夜了吗?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值