事件(event)
事件系统允许你向后端发送事件,或者是监听来自后端的事件。
当在 tauri.conf.json 中设置 build.withGlobalTauri
为 true
时,该包也可以通过 window.__TAURI__.event
访问。
Enumerations
TauriEvent
Since: 1.1.0
枚举成员
名称 |
类型 |
定义在 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Interfaces
Event<T>
类型参数
-
T
属性
-
event:
EventName
事件名称。
定义在: helpers/event.ts:12
-
id:
number
用来取消监听的事件唯一标识符。
定义在: helpers/event.ts:16
-
payload:
T
事件消息体
定义在: helpers/event.ts:18
-
windowLabel:
string
发出此事件的窗口的标签。
定义在: helpers/event.ts:14
Type Aliases
EventCallback<T>
-
EventCallback<
T
>: (event
:Event
<T
>) ⇒void
类型参数
-
T
类型声明
-
(
event
:Event
<T
>):void
参数
名称 |
类型 |
|
|
返回: void
定义在: helpers/event.ts:21
Functions
emit
-
emit(
event
:string
,payload?
:unknown
):Promise
<void
>
向后端发送一个事件。
示例
import { emit } from '@tauri-apps/api/event';
await emit('frontend-loaded', { loggedIn: true, token: 'authToken' });
Since: 1.0.0
参数
名称 |
类型 |
描述 |
|
|
事件名称。只能包含字母、数字、 |
|
|
- |
返回: Promise
<void
>
listen
-
listen<
T
>(event
:EventName
,handler
:EventCallback
<T
>):Promise
<UnlistenFn
>
监听来自后端的事件。
示例
import { listen } from '@tauri-apps/api/event';
const unlisten = await listen<string>('error', (event) => {
console.log(`Got error in window ${event.windowLabel}, payload: ${event.payload}`);
});
// you need to call unlisten if your handler goes out of scope e.g. the component is unmounted
unlisten();
Since: 1.0.0
类型参数
-
T
参数
名称 |
类型 |
描述 |
|
事件名称。只能包含字母、数字、 |
|
|
事件回调句柄。 |
返回: Promise
<UnlistenFn
>
一个 Promise,解析为一个函数,用于取消事件监听。请注意,如果你的监听器超出作用域,例如组件卸载,必须移除监听器。
once
-
once<
T
>(event
:EventName
,handler
:EventCallback
<T
>):Promise
<UnlistenFn
>
监听来自后端的一次性事件。
示例
import { once } from '@tauri-apps/api/event';
interface LoadedPayload {
loggedIn: boolean,
token: string
}
const unlisten = await once<LoadedPayload>('loaded', (event) => {
console.log(`App is loaded, loggedIn: ${event.payload.loggedIn}, token: ${event.payload.token}`);
});
// you need to call unlisten if your handler goes out of scope e.g. the component is unmounted
unlisten();
Since: 1.0.0
类型参数
-
T
参数
名称 |
类型 |
描述 |
|
事件名称。只能包含字母、数字、 |
|
|
- |
返回: Promise
<UnlistenFn
>
一个 Promise,解析为一个函数,用于取消事件监听。请注意,如果你的监听器超出作用域,例如组件卸载,必须移除监听器。