Using Watchers to React to Data Changes
Set up a watcher to monitor changes in a data property and perform actions like data validation or logging.
<div id="app">
<input v-model="message" placeholder="Edit me">
<p>Message is: {{ message }}</p>
</div>
HTML structure with a Vue.js data binding. A text input is bound to a Vue instance data property 'message'.
<style>
.valid {
color: green;
}
.invalid {
color: red;
}
</style>
CSS styles defining valid (green) and invalid (red) text color for data validation feedback.
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script>
new Vue({
el: '#app',
data: function() {
return {
message: ''
};
},
watch: {
// Watcher on the 'message' data property
message: function (newValue, oldValue) {
console.log(`Message changed from ${oldValue} to ${newValue}`);
this.validateMessage(newValue);
}
},
methods: {
// A method to validate the message
validateMessage: function (message) {
if (this.isValidMessage(message)) {
this.setMessageValidity(true);
} else {
this.setMessageValidity(false);
}
},
// Method to check if the message is valid
isValidMessage: function (message) {
// Placeholder validation logic
return message.length > 3;
},
// Apply valid/invalid CSS class based on validity
setMessageValidity: function (isValid) {
const inputElement = this.$el.querySelector('input');
if (isValid) {
inputElement.classList.remove('invalid');
inputElement.classList.add('valid');
} else {
inputElement.classList.remove('valid');
inputElement.classList.add('invalid');
}
}
}
});
</script>
JavaScript with Vue.js framework. It includes a Vue instance with a watcher on the 'message' data property and methods for validating and styling the message based on its validity.