当状态变化后,你不是想“显示一个新值”,而是想做点额外动作:
- 发请求
- 写本地存储
- 打日志
- 操作第三方库
这时用 watch() 或 watchEffect()。
<script setup lang="ts">
import { ref, watch, onWatcherCleanup } from 'vue';
const keyword = ref('vue');
const shops = ref<any[]>([]);
watch(
keyword,
async (q) => {
const controller = new AbortController();
onWatcherCleanup(() => {
controller.abort();
});
const res = await fetch(`/api/shops?q=${q}`, {
signal: controller.signal,
});
shops.value = await res.json();
},
{ immediate: true }
);
</script>watch |
watchEffect |
|
|---|---|---|
| 依赖来源 | 手动指定 | 自动收集 |
| 控制力 | 更精确 | 更省事 |
| 更适合 | 明确侦听某几个值 | 快速写副作用逻辑 |
如果 computed 是自动电子招牌,那 watch / watchEffect 就是街区巡检队。