// Vue 3 watch 示例代码
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref, watch } from 'vue';
export default {
setup() {
const count = ref(0);
// 定义一个方法来改变 count 的值
const increment = () => {
count.value++;
};
// 使用 watch 监听 count 的变化
watch(count, (newVal, oldVal) => {
console.log(`count changed from ${oldVal} to ${newVal}`);
});
return {
count,
increment
};
}
};
</script>
模板部分 (<template>):
count 值。increment 方法增加 count。脚本部分 (<script>):
ref 创建一个响应式的 count 变量,初始值为 0。increment 方法,每次点击按钮时将 count 的值加 1。watch 监听 count 的变化。每当 count 发生变化时,会触发回调函数,并打印出旧值和新值。返回对象:
count 和 increment 方法暴露给模板使用。上一篇:vue3 tsx
下一篇:vue3setup语法糖
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站