You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue组件无法响应自定义Hook内ref的变更,求排查解决

问题原因及解决方法

你的问题出在自定义Hook里的suggestions被声明成了全局变量——它定义在Hook函数的外部,导致所有调用该Hook的组件共享同一个ref实例,同时组件内的watch无法正确绑定到当前组件的响应式上下文,自然监听不到变更。

修正后的Hook代码

// useCustomHook.ts
export function useCustomHook() {
  // 把ref声明移到Hook函数内部,确保每次调用都生成独立的响应式状态
  const suggestions = ref([]);

  watch(suggestions, () => console.log({ suggestions: suggestions.value }));

  return {
    suggestions
  };
}

组件代码修正(补全语法错误)

// VueComponent.vue
<script setup lang="ts">
import { useCustomHook } from './useCustomHook';

const { suggestions } = useCustomHook();

// 补全闭合括号,打印ref的value更直观
watch(suggestions, () => console.log({ suggestions: suggestions.value }));
</script>

额外说明

如果你的业务需要监听数组内部元素的原地修改(比如push、splice这类操作),可以给watch添加deep: true选项:

watch(suggestions, () => { /* 回调逻辑 */ }, { deep: true });

内容的提问来源于stack exchange,提问作者Massaget

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 07:35:10