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

发布时间 2023-05-26 10:56:52作者: 槑孒

在使用 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来定义方法。