在使用 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 踩坑记录
箴言:因为这些东西是非常简单的。不要抱怨自己学不会,那是因为你没有足够用心。