Vue3 watch API 踩坑记录 | 方法未定义问题

在使用 setup() 语法糖时,方法的定义和 watch 的调用都在 setup内部进行。

需要确保方法在 watch 调用之前可访问。

错误示例

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    info: any;
  }>(),
  {}
);
watch(
  () => props.info,
  () => {
    test();
  },
  { deep: true, immediate: true }
);
const test = () => {
  console.log("ok");
};
</script>

这个时候,会报错Uncaught (in promise) ReferenceError: Cannot access 'test' before initialization

原因就是test方法在 watch 调用之前还不可访问。

解决方法一:

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    info: any;
  }>(),
  {}
);
const test = () => {
  console.log("ok");
};
watch(
  () => props.info,
  () => {
    test();
  },
  { deep: true, immediate: true }
);
</script>

调整方法与watch的先后顺序。

解决方法二:

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    info: any;
  }>(),
  {}
);
watch(
  () => props.info,
  () => {
    test();
  },
  { deep: true, immediate: true }
);
function test(){
  console.log("ok");
};

</script>

使用function来定义方法。

Vue3 watch API 踩坑记录

posted @   槑孒  阅读(975)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示