Watching reactive dependencies
Demonstrate the setup of watchers in a component using both the Options API's watch option and the Composition API's watch function.
// Vue 2 with Options API
new Vue({
data() {
return {
myReactiveProperty: ''
};
},
watch: {
myReactiveProperty(newValue, oldValue) {
console.log(`myReactiveProperty changed from ${oldValue} to ${newValue}`);
}
},
methods: {
updateProperty(newValue) {
this.myReactiveProperty = newValue;
}
}
});
This code snippet is for Vue 2, using the Options API. It sets up a watcher on 'myReactiveProperty' within a Vue component, and defines a method to update it. When 'myReactiveProperty' changes, the watcher logs the old and new value.
// Vue 3 with Composition API
import { ref, watch } from 'vue';
export default {
setup() {
const myReactiveProperty = ref('');
watch(myReactiveProperty, (newValue, oldValue) => {
console.log(`myReactiveProperty changed from ${oldValue} to ${newValue}`);
});
function updateProperty(newValue) {
myReactiveProperty.value = newValue;
}
return {
myReactiveProperty,
updateProperty
};
}
};
This code snippet is for Vue 3, using the Composition API. It defines 'myReactiveProperty' as a reactive reference, sets up a watcher for it, and provides an 'updateProperty' function to modify its value. The watcher logs changes to the console.