InterviewSolution
| 1. |
Based on the code below, when would the value for ‘answer’ instance compute either yes or no? Which Vue.js feature is used for initiating the action? |
|
Answer» <script> export default { data() { return { question: '', answer: 'Questions mostly contain question mark' } }, watch: { question(newQuestion, oldQuestion) { if (newQuestion.indexOf('?') > -1) { this.getAnswer() } } }, methods: { async getAnswer() { this.answer = 'Thinking...' try { const res = await fetch('https://yesno.wtf/api') this.answer = (await res.json()).answer } catch (e) { this.answer = 'Error! Could not reach the API. ' + error } } } } </script> <template> <p> Ask a yes/no question: <input v-model="question" /> </p> <p>{{ answer }}</p> </template>
Defining watch, the FUNCTION that prevents the modification in the state should have the same NAME as the reactive instance. In this case, it is observed that the function name has two parameters (newQuestion, oldQuestion) . If the function's name DIFFERS from the reactive instance, nothing will happen to the value of the 'answer' even if the question is modified and the question mark is included. |
|