Skip to content

useOnce

Introduction

确保回调函数只执行一次

TIP

例如,有一个函数向服务器发送加载数据的请求。使用useOnce(),可以确保请求不会被多次执行。

即使用户一直点击该按钮,这也将避免性能问题,并确认请求只执行一次。

Basic Usage

ts
import { useOnce } from '@flypeng/tool/browser';

const sendRequestOnce = useOnce(() => {
  console.log('execute only once');
});
const button = document.querySelector('button');
button.addEventListener('click', sendRequestOnce);

Type Declaration

ts
/**
 * 保证函数只执行一次
 * @param callback
 * @returns
 */
declare function useOnce(callback: () => void): () => void;

Online Demo

useOnce
确保回调函数只执行一次
<template>
  <button ref="buttonSend" @click="sendRequestOnce" :disabled="message === '未发送请求' ? false : true">
    点击发送请求
  </button>
</template>

<script lang="ts" setup>
import { useOnce } from '@flypeng/tool/browser';
import { ref } from 'vue';

const message = ref<'未发送请求' | '已发生请求'>('未发送请求');

const sendRequestOnce = useOnce(() => {
  message.value = '已发生请求';
});
</script>

<style scoped>
button {
  border-radius: 4px;
  color: #ffffff;
  background-color: var(--vp-c-brand);
  padding: 4px 8px;
  margin: 10px 0;
}
button:disabled {
  background-color: var(--vp-c-disabled-bg);
  cursor: not-allowed;
}
</style>

Released under the MIT License.