NaiveUI-useMessage报错
NaiveUI很多组件虽然需要手动操作,但根据个人体验,认为该UI库性能方面的确比较时髦,无愧于新生代的UI组件库。
解决办法
单独新建Message.vue组件,将message挂载在window。
<template>
<div></div>
</template>
<script lang="ts" setup>
import { useMessage } from 'naive-ui';
window.$message = useMessage();
</script>
同时需要在xxx.d.ts中添加window相关声明
types>global.d.ts
declare global是为了在全局命名空间做声明,比如为对象增加一个未定义的属性。
import type { PropType as VuePropType } from 'vue';
import { App } from 'vue';
import type { DialogApiInjection } from 'naive-ui/lib/dialog/src/DialogProvider';
import type { MessageApiInjection } from 'naive-ui/lib/message/src/MessageProvider';
// GlobalComponents for Volar
declare global {
interface Window {
// Global vue app instance
__APP__: App<Element>;
webkitCancelAnimationFrame: (handle: number) => void;
mozCancelAnimationFrame: (handle: number) => void;
oCancelAnimationFrame: (handle: number) => void;
msCancelAnimationFrame: (handle: number) => void;
webkitRequestAnimationFrame: (callback: FrameRequestCallback) => number;
mozRequestAnimationFrame: (callback: FrameRequestCallback) => number;
oRequestAnimationFrame: (callback: FrameRequestCallback) => number;
msRequestAnimationFrame: (callback: FrameRequestCallback) => number;
}
interface Window {
$message: MessageApiInjection;
$dialog: DialogApiInjection;
}
// vue
type PropType<T> = VuePropType<T>;
type Writable<T> = {
-readonly [P in keyof T]: T[P];
};
type Nullable<T> = T | null;
type Recordable<T = any> = Record<string, T>;
type ReadonlyRecordable<T = any> = {
readonly [key: string]: T;
};
type Indexable<T = any> = {
[key: string]: T;
};
type DeepPartial<T> = {
[P in keyof T]?: DeepPartial<T[P]>;
};
type TimeoutHandle = ReturnType<typeof setTimeout>;
type IntervalHandle = ReturnType<typeof setInterval>;
interface ChangeEvent extends Event {
target: HTMLInputElement;
}
interface WheelEvent {
path?: EventTarget[];
}
function parseInt(s: string | number, radix?: number): number;
function parseFloat(string: string | number): number;
}
在App.vue入口文件中进行挂载。
<template>
<n-message-provider>
<MessageApi />
</n-message-provider>
<router-view></router-view>
</template>
<script setup lang="ts">
import { NMessageProvider } from 'naive-ui';
import MessageApi from './components/Message/index.vue';
</script>
<style>
#app {
height: 100%;
color: #2c3e50;
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
</style>
实际项目中的使用
通过 window.$message.提示类型即可在全局使用。
const paneChange = (e) => {
window.$message.success('退出成功!');
initPane.value = e;
paneLine.value = e * 130 + 'px';
console.log(e);
};