跳至主要內容

事件

事件系統允許您發出事件到後端,並從後端接收事件。

tauri.conf.json 中的 build.withGlobalTauri 設為 true 時,也可以使用 window.__TAURI__.event 存取這個套件。

列舉

TauriEvent

: 1.1.0

列舉成員

名稱類型定義於
"tauri://update"event.ts:34
"tauri://update-download-progress"event.ts:38
"tauri://update-install"event.ts:36
"tauri://menu"event.ts:33
"tauri://update-status"event.ts:37
"tauri://update-available"event.ts:35
"tauri://blur"event.ts:27
"tauri://close-requested"event.ts:23
"tauri://window-created"event.ts:24
"tauri://destroyed"event.ts:25
"tauri://file-drop"event.ts:30
"tauri://file-drop-cancelled"event.ts:32
"tauri://file-drop-hover"event.ts:31
"tauri://focus"event.ts:26
"tauri://move"event.ts:22
"tauri://resize"event.ts:21
"tauri://scale-change"event.ts:28
"tauri://theme-changed"event.ts:29

介面

Event<T>

類型參數

  • T

屬性

event

event: EventName

事件名稱

定義於: helpers/event.ts:12

id

識別碼數字

用於取消監聽的事件識別碼

定義於: helpers/event.ts:16

payload

payloadT

事件 payload

定義於: helpers/event.ts:18

windowLabel

windowLabel字串

發出此事件的視窗標籤。

定義於: helpers/event.ts:14

類型別名

EventCallback<T>

EventCallback<T>: (eventEvent<T>) => void

類型參數

  • T

類型宣告

(eventEvent<T>): void

參數

名稱類型
事件Event<T>

傳回:void

定義於: helpers/event.ts:21

EventName

EventName${TauriEvent} | 字串 & Record<never, never>

定義於: event.ts:15

UnlistenFn

UnlistenFn: () => void

類型宣告

(): void

傳回:void

定義於: helpers/event.ts:23

函式

emit

emit(event: string, payload?: unknown): Promise<void>

向後端和所有 Tauri 視窗發出事件。

範例

import { emit } from '@tauri-apps/api/event';
await emit('frontend-loaded', { loggedIn: true, token: 'authToken' });

: 1.0.0

參數

名稱類型說明
事件字串事件名稱。只能包含字母數字字元、-/:_
payload?未知-

傳回: Promise<void>

listen

listen<T>(event: EventName, handler: EventCallback<T>): Promise<UnlistenFn>

聆聽事件。事件可以是全域或視窗特定。請參閱 windowLabel 以檢查事件來源。

範例

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();

: 1.0.0

類型參數

  • T

參數

名稱類型說明
事件EventName事件名稱。只能包含字母數字字元、-/:_
handlerEventCallback<T>事件處理常式回呼。

傳回: Promise<UnlistenFn>

承諾解析為取消聆聽事件的函式。請注意,如果您的聆聽器超出範圍,例如卸載元件,則必須移除聆聽器。

once

once<T>(event: EventName, handler: EventCallback<T>): Promise<UnlistenFn>

聆聽一次性事件。請參閱 listen 以取得更多資訊。

範例

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();

: 1.0.0

類型參數

  • T

參數

名稱類型說明
事件EventName事件名稱。只能包含字母數字字元、-/:_
handlerEventCallback<T>-

傳回: Promise<UnlistenFn>

承諾解析為取消聆聽事件的函式。請注意,如果您的聆聽器超出範圍,例如卸載元件,則必須移除聆聽器。