useEvent
消息机制
何时使用
当需要全局消息机制时
API
const {
set,
setOnce,
off,
clear,
trigger
} = useEvent(namespace: string);
返回值说明
返回值 | 说明 | 类型 |
---|---|---|
set | 监听一个或多个事件 | (eventName: string, ...handlers: Noop[]) => void |
setOnce | 监听一个或多个事件一次(触发后自动移除) | (eventName: string, ...handlers: Noop[]) => void |
off | 取消监听一个或多个事件一次 | (eventName: string, ...handlers: Noop[]) => void |
clear | 取消所有事件监听 | () => void |
trigger | 触发事件并传入参数 | (eventName: string, ...params: any[]) => void |
代码演示
- React
- Vue
basic/useEvent/index
import React from 'react';
import { useEvent, useModal } from 'taro-hooks';
import DemoContent from '@src/components/DemoContent';
import { Button } from '@taroify/core';
export default () => {
const show = useModal({ title: 'useEvent', showCancel: false });
const { set, setOnce, off, clear, trigger } = useEvent('useEvent');
const eventName = 'event';
const eventOneceName = 'event-once';
const listener = (params) => {
show({ content: '事件触发成功: ${String(params)}' });
};
return (
<DemoContent>
<Button
className="gap"
block
color="primary"
onClick={() => set(eventName, listener)}
shape="square"
>
设置监听
</Button>
<Button
className="gap"
block
color="primary"
onClick={() => trigger(eventName)}
shape="square"
>
触发监听
</Button>
<Button
className="gap"
block
color="primary"
onClick={() => setOnce(eventOneceName, listener)}
shape="square"
>
设置监听(仅触发一次)
</Button>
<Button
className="gap"
block
color="primary"
onClick={() => trigger(eventOneceName, 'once')}
shape="square"
>
触发监听(仅触发一次)
</Button>
<Button
className="gap"
block
color="primary"
onClick={() => off(eventName)}
shape="square"
>
移除监听
</Button>
<Button
className="gap"
block
color="primary"
onClick={() => clear()}
shape="square"
>
清除所有监听
</Button>
</DemoContent>
);
};
basic/useEvent/index
<template>
<demo-content>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="set(eventName, listener)"
>设置监听</nut-button
>
<nut-button
shape="square"
type="primary"
block
class="gap"
@click="trigger(eventName)"
>触发监听</nut-button
>
<nut-button
shape="square"
type="primary"
block
class="gap"
@click="setOnce(eventOneceName, listener)"
>设置监听(仅触发一次)</nut-button
>
<nut-button
shape="square"
type="primary"
block
class="gap"
@click="trigger(eventOneceName, 'once')"
>触发监听(仅触发一次)</nut-button
>
<nut-button
shape="square"
type="primary"
block
class="gap"
@click="off(eventName)"
>移除监听</nut-button
>
<nut-button shape="square" type="primary" block class="gap" @click="clear()"
>清除所有监听</nut-button
>
</demo-content>
</template>
<script setup lang="ts">
import { useEvent, useModal } from 'taro-hooks';
const show = useModal({ title: 'useEvent', showCancel: false, mask: true });
const { set, setOnce, off, clear, trigger } = useEvent('useEvent');
const eventName = 'event';
const eventOneceName = 'event-once';
const listener = (params) => {
show({ content: '事件触发成功: ${String(params)}' });
};
</script>
Hook 支持度
微信小程序 | H5 | ReactNative |
---|---|---|
✔️ | ✔️ | ✔️ |