// 使用 watch 和 watchEffect 的示例代码
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref, watch, watchEffect } from 'vue';
export default {
setup() {
const count = ref(0);
// 使用 watch 监听特定的响应式数据变化
watch(count, (newVal, oldVal) => {
console.log(`watch: count changed from ${oldVal} to ${newVal}`);
});
// 使用 watchEffect 立即执行并监听所有依赖的变化
watchEffect(() => {
console.log(`watchEffect: count is ${count.value}`);
});
const increment = () => {
count.value++;
};
return {
count,
increment
};
}
};
</script>
watch
:
watch
用于监听特定的响应式数据(如 ref
或 reactive
对象)的变化。watchEffect
:
watchEffect
会立即执行传入的函数,并自动追踪其中用到的所有响应式依赖。watchEffect
会重新执行该函数。通过上述代码和解释,你可以更好地理解 watch
和 watchEffect
在 Vue 3 中的区别。
上一篇:vue teleport
下一篇:vue3 i18n
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站