Reputation: 21
We are creating an webapp to watch for analytical changes and update them in real time, (this shouldn't be important just figured I'd let you know.)
On Vue.js's offical website https://v3.vuejs.org/guide/computed.html#computed-caching-vs-methods they have an example of using watchers.
Code:
<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question" />
</p>
<p>{{ answer }}</p>
</div>
<!-- Since there is already a rich ecosystem of ajax libraries -->
<!-- and collections of general-purpose utility methods, Vue core -->
<!-- is able to remain small by not reinventing them. This also -->
<!-- gives you the freedom to use what you're familiar with. -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
<script>
const watchExampleVM = Vue.createApp({
data() {
return {
question: '',
answer: 'Questions usually contain a question mark. ;-)'
}
},
watch: {
// whenever question changes, this function will run
question(newQuestion, oldQuestion) {
if (newQuestion.indexOf('?') > -1) {
this.getAnswer()
}
}
},
methods: {
getAnswer() {
this.answer = 'Thinking...'
axios
.get('https://yesno.wtf/api')
.then(response => {
this.answer = response.data.answer
})
.catch(error => {
this.answer = 'Error! Could not reach the API. ' + error
})
}
}
}).mount('#watch-example')
</script>
In the code you can see the variables Old Question and New Question, so the question is how does it know the values of those 2 when they are never defined?
We did try and import this into our project just to see if the website itself was giving it the values, however, after seeing that it worked (with minimal changes) we did not believe this was the case. Any help would be much appreciated.
-Shark
Upvotes: 2
Views: 49
Reputation: 3440
So they are not defined because these are not variables but instead parameters. The watcher always receives 2 parameters. The old value and the new value.
When you type into the input <input v-model="question" />
which is bound with v-model to question
the value of question
changes, this will trigger the watcher with the new value and the old value to which you can run logic on. You could use a watcher on something like fullName
and look for spaces and set this.firstName
and this.lastName
or like the example is doing, looking for the value of a question mark to trigger a method.
Upvotes: 2