怎么判断网站有没有做百度商桥培训报名
前言
在 Vue 3 中,可以使用
watch
函数来观察响应式数据的变化。这个函数可以在组件的setup
函数中使用。watch()
方法还可以实现更多复杂的功能,比如异步获取数据并在数据更新时重新渲染页面。
代码示例
1、以下是一个使用 Vue 3 watch
函数的简单示例:
<template><div><p>Count: {{ count }}</p><button @click="increment">Increment</button></div>
</template><script>
import { ref, watch, defineComponent } from 'vue';export default defineComponent({setup() {const count = ref(0);// 定义一个方法用于增加 countfunction increment() {count.value++;}// 使用 watch 函数来观察响应式数据 count 的变化watch(count, (newValue, oldValue) => {console.log(`Count changed from ${oldValue} to ${newValue}`);});return {count,increment,};},
});
</script>
2、多个变量的监听:
除了单个变量的监听,watch()还可以监听多个变量的变化,以及获取旧值/新值的情况。多个变量的监听:// 使用 watch 函数来观察响应式数据 count 的变化watch([count1,count2], ([newcount1, newcount2],[oldcount1,oldcount2]) => {console.log(`Count changed from ${oldcount1} to ${newcount1}`);console.log(`Count changed from ${oldcount2} to ${newcount2}`);},
{deep:true}
);
在这个例子中,我们传递了一个选项对象,用于开启深层监听。这种方式可以使watch()监听的变量案例更加庞大复杂。