Vue 3.x 使用 watch
函数:
<template>
<div>{{ myObject.property }}</div>
</template>
<script>
import { reactive, watch } from 'vue';
export default {
setup() {
const myObject = reactive({ property: 'initial value' });
watch(myObject, (newValue, oldValue) => {
console.log('Object changed:', newValue);
});
return { myObject };
},
};
</script>
Vue 2.x 使用 watch
选项:
<template>
<div>{{ myObject.property }}</div>
</template>
<script>
export default {
data() {
return {
myObject: { property: 'initial value' }
};
},
watch: {
myObject: {
handler(newValue, oldValue) {
console.log('Object changed:', newValue);
},
deep: true // 监听对象内部的属性变化
}
}
};
</script>