App.vue
main.js
<template>
<h2>Example $watch() Method</h2>
<p>The watcher is set up to watch 'value.country' and will therefore detect when the country is changed inside the 'value' object.</p>
<div>
<p>Register a new country for Stuart to live in:</p>
<p><input type="text" v-model="inpVal"></p>
<button v-on:click="regHobby">Register</button>
<ol>
<li v-for="x in watchMessages">{{ x }}</li>
</ol>
</div>
<p>Current 'value' object:</p>
<pre>{{ this.value }}</pre>
</template>
<script>
export default {
data() {
return {
inpVal: null,
value: {
owner: 'Stuart',
address: 'Faraway Lane',
country: 'Mexico'
},
watchMessages: []
};
},
methods: {
regHobby() {
this.value.country = this.inpVal;
this.inpVal = null;
}
},
mounted() {
this.$watch('value.country', function () {
this.watchMessages.push('watcher triggered')
});
}
};
</script>
<style scoped>
div {
border: solid black 1px;
padding: 10px;
}
li {
background-color: lightgreen;
}
</style>
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.mount('#app')