跳到内容
SCRM DOC
HooksVue3Core创建于2026-01-10更新于 2026-01-10

Core Hooks 核心功能

概述

Core Hooks 提供基础且核心的 Vue 3 工具函数,包括函数锁、引用管理、属性处理等。

导入方式

import { useLockFn, useRefs, useAttrs, useContext, useTimeout } from '@/hooks/core';

1. useLockFn 函数锁

防止异步函数被重复执行,适用于提交按钮、下载等场景。

类型定义

function useLockFn<P extends any[] = any[], V extends any = any>(
  fn: (...args: P) => Promise<V>
): (...args: P) => Promise<V>

使用示例

<template>
  <div class="lock-demo">
    <a-button @click="handleSubmit" :loading="loading">
      提交表单
    </a-button>

    <a-button @click="handleDownload" :loading="downloading">
      下载文件
    </a-button>

    <a-button @click="handleReset">
      重置状态
    </a-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useLockFn } from '@/hooks/core';
import { useMessage } from '@/hooks/web';

const { createMessage } = useMessage();
const loading = ref(false);
const downloading = ref(false);

// 防止重复提交
const handleSubmit = useLockFn(async () => {
  loading.value = true;
  try {
    // 模拟 API 请求
    await new Promise(resolve => setTimeout(resolve, 2000));
    createMessage.success('提交成功');
  } finally {
    loading.value = false;
  }
});

// 防止重复下载
const handleDownload = useLockFn(async () => {
  downloading.value = true;
  try {
    await downloadFile();
    createMessage.success('下载成功');
  } finally {
    downloading.value = false;
  }
});

// 普通函数不会被锁
const handleReset = () => {
  console.log('可以多次点击');
};

async function downloadFile() {
  // 下载逻辑
  await new Promise(resolve => setTimeout(resolve, 1500));
}
</script>

实际应用场景

// 1. 表单提交
const submitForm = useLockFn(async (formData) => {
  await api.submitForm(formData);
  createMessage.success('提交成功');
});

// 2. 数据加载
const loadData = useLockFn(async () => {
  const data = await api.fetchData();
  return data;
});

// 3. 文件上传
const uploadFile = useLockFn(async (file) => {
  await api.upload(file);
  createMessage.success('上传成功');
});

// 4. 支付操作
const handlePay = useLockFn(async (orderId) => {
  await api.pay(orderId);
  createMessage.success('支付成功');
});

2. useRefs 多引用管理

管理多个 DOM 元素或组件引用。

类型定义

function useRefs(): [
  Ref<HTMLElement[]>,  // refs 数组
  (index: number) => (el: HTMLElement) => void  // setRefs 函数
]

使用示例

<template>
  <div class="refs-demo">
    <div v-for="(item, index) in items" :key="index" :ref="setRefs(index)">
      {{ item }}
    </div>

    <a-button @click="scrollToItem(2)">滚动到第3项</a-button>
    <a-button @click="highlightAll">高亮所有</a-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRefs } from '@/hooks/core';

const items = ref(['项目1', '项目2', '项目3', '项目4', '项目5']);
const [refs, setRefs] = useRefs();

// 滚动到指定项
const scrollToItem = (index: number) => {
  const element = refs.value[index];
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }
};

// 高亮所有元素
const highlightAll = () => {
  refs.value.forEach((el) => {
    if (el) {
      el.style.background = 'yellow';
    }
  });
};

// 访问特定索引的元素
const getItemElement = (index: number) => {
  return refs.value[index];
};
</script>

动态列表使用

<template>
  <div class="dynamic-refs">
    <div
      v-for="(item, index) in dynamicItems"
      :key="item.id"
      :ref="setRefs(index)"
      class="item"
    >
      {{ item.name }}
    </div>

    <a-button @click="addItem">添加项</a-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRefs } from '@/hooks/core';

interface Item {
  id: number;
  name: string;
}

const dynamicItems = ref<Item[]>([
  { id: 1, name: '项目1' },
  { id: 2, name: '项目2' },
]);

const [refs, setRefs] = useRefs();

const addItem = () => {
  const newId = dynamicItems.value.length + 1;
  dynamicItems.value.push({ id: newId, name: `项目${newId}` });
};
</script>

3. useAttrs 属性处理

处理组件属性透传和合并。

使用示例

<template>
  <div>
    <!-- 基础组件 -->
    <MyInput v-bind="attrs" />
  </div>
</template>

<script setup lang="ts">
import { useAttrs } from 'vue';

const attrs = useAttrs();

// attrs 包含所有未在 props 中声明的属性
console.log(attrs);
</script>

包装组件使用

<template>
  <a-input
    :value="value"
    :class="attrs.class"
    :style="attrs.style"
    v-bind="restAttrs"
    @input="handleInput"
  />
</template>

<script setup lang="ts">
import { useAttrs, computed } from 'vue';

interface Props {
  value?: string;
}

const props = defineProps<Props>();
const emit = defineEmits(['update:value', 'input']);

const attrs = useAttrs();

// 分离 class 和 style
const { class: cls, style, ...restAttrs } = attrs as any;

const handleInput = (e: Event) => {
  const value = (e.target as HTMLInputElement).value;
  emit('update:value', value);
  emit('input', value);
};
</script>

4. useContext 上下文处理

跨层级组件通信。

使用示例

// 父组件
import { provide } from 'vue';
import { useContext } from '@/hooks/core';

const contextData = {
  theme: ref('light'),
  locale: ref('zh-CN'),
};

provide('app-context', contextData);

// 子组件
import { inject } from 'vue';
import { useContext } from '@/hooks/core';

const context = useContext('app-context');
console.log(context.theme.value); // 'light'
console.log(context.locale.value); // 'zh-CN'

创建自定义上下文 Hook

// hooks/useAppContext.ts
import { inject, provide, computed } from 'vue';
import { useContext } from '@/hooks/core';

const CONTEXT_KEY = 'app-context';

export function useAppProvider() {
  const theme = ref('light');
  const locale = ref('zh-CN');

  const context = {
    theme,
    locale,
    isDark: computed(() => theme.value === 'dark'),
  };

  provide(CONTEXT_KEY, context);

  return context;
}

export function useAppContext() {
  return useContext(CONTEXT_KEY);
}

// 在主应用中
const appContext = useAppProvider();

// 在子组件中
const { theme, isDark } = useAppContext();

5. useTimeout 定时器

管理 setTimeout 的 Hook,自动清理定时器。

使用示例

<template>
  <div class="timeout-demo">
    <a-button @click="startTimeout">开始倒计时</a-button>
    <a-button @click="clearTimeout">清除定时器</a-button>

    <p>剩余时间: {{ seconds }}秒</p>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useTimeout } from '@/hooks/core';

const seconds = ref(10);
const { start, clear } = useTimeout(() => {
  console.log('定时器触发');
}, 1000);

const startTimeout = () => {
  start(); // 开始定时器
};

const clearTimeoutFn = () => {
  clear(); // 清除定时器
};

// 自动清理(组件卸载时)
onUnmounted(() => {
  clear();
});
</script>

倒计时实现

<script setup lang="ts">
import { ref } from 'vue';
import { useTimeout } from '@/hooks/core';

const count = ref(60);
const { start, clear } = useTimeout(() => {
  if (count.value > 0) {
    count.value--;
    start(); // 递归调用
  }
}, 1000);

// 开始倒计时
const startCountdown = () => {
  count.value = 60;
  start();
};

// 清除倒计时
const clearCountdown = () => {
  clear();
  count.value = 60;
};
</script>

6. onMountedOrActivated

在组件挂载或激活时执行(支持 keep-alive)。

使用示例

<script setup lang="ts">
import { onMountedOrActivated } from '@/hooks/core';
import { ref } from 'vue';

const data = ref([]);

onMountedOrActivated(() => {
  console.log('组件已挂载或激活');
  loadData();
});

async function loadData() {
  // 加载数据逻辑
  const response = await api.fetchData();
  data.value = response.data;
}
</script>

与 keep-alive 配合

<template>
  <keep-alive>
    <MyComponent v-if="showComponent" />
  </keep-alive>
</template>

<script setup lang="ts">
// MyComponent.vue
import { onMountedOrActivated, onUnmounted } from '@/hooks/core';

let timer: any;

onMountedOrActivated(() => {
  console.log('组件激活');
  startPolling();
});

onUnmounted(() => {
  console.log('组件卸载');
  stopPolling();
});

function startPolling() {
  timer = setInterval(() => {
    // 轮询逻辑
  }, 5000);
}

function stopPolling() {
  if (timer) {
    clearInterval(timer);
  }
}
</script>

完整示例

<template>
  <div class="core-hooks-demo">
    <a-card title="useLockFn 示例">
      <a-space>
        <a-button @click="handleSubmit" :loading="loading">
          提交
        </a-button>
        <a-button @click="handleDownload" :loading="downloading">
          下载
        </a-button>
      </a-space>
    </a-card>

    <a-card title="useRefs 示例" style="margin-top: 16px">
      <div v-for="(item, index) in items" :key="index" :ref="setRefs(index)" class="item">
        {{ item }}
      </div>
      <a-button @click="scrollToItem(2)" style="margin-top: 8px">
        滚动到第3项
      </a-button>
    </a-card>

    <a-card title="useTimeout 示例" style="margin-top: 16px">
      <a-space>
        <a-button @click="startCountdown">开始倒计时</a-button>
        <span>剩余: {{ count }}秒</span>
      </a-space>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useLockFn, useRefs, useTimeout } from '@/hooks/core';
import { useMessage } from '@/hooks/web';

const { createMessage } = useMessage();
const loading = ref(false);
const downloading = ref(false);
const count = ref(10);

// useLockFn
const handleSubmit = useLockFn(async () => {
  loading.value = true;
  await new Promise(resolve => setTimeout(resolve, 2000));
  createMessage.success('提交成功');
  loading.value = false;
});

const handleDownload = useLockFn(async () => {
  downloading.value = true;
  await new Promise(resolve => setTimeout(resolve, 1500));
  createMessage.success('下载成功');
  downloading.value = false;
});

// useRefs
const items = ref(['项目1', '项目2', '项目3', '项目4', '项目5']);
const [refs, setRefs] = useRefs();

const scrollToItem = (index: number) => {
  const element = refs.value[index];
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'center' });
    element.style.background = 'yellow';
    setTimeout(() => {
      element.style.background = '';
    }, 2000);
  }
};

// useTimeout
const { start: startCountdownTimer } = useTimeout(() => {
  if (count.value > 0) {
    count.value--;
    startCountdownTimer();
  }
}, 1000);

const startCountdown = () => {
  count.value = 10;
  startCountdownTimer();
};
</script>

<style scoped>
.item {
  padding: 8px;
  margin: 4px 0;
  background: #f5f5f5;
  border-radius: 4px;
  transition: all 0.3s;
}
</style>

注意事项

  1. useLockFn:只适用于异步函数,同步函数无需使用
  2. useRefs:在 v-for 中使用时,确保索引稳定
  3. useTimeout:组件卸载时自动清理,无需手动清理
  4. useContext:确保 provide 和 inject 的 key 一致
  5. onMountedOrActivated:配合 keep-alive 使用,替代 onMounted

相关文档


文档版本: 1.0.0 最后更新: 2026-01-10

本页目录