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> 

  • The computation of the 'answer' instance to either 'yes' or 'no' will be triggered when the question's value changes to a new one and the question mark is included in the question. Otherwise, the 'answer' value will remain as 'Questions usually contain a question mark.' 
  • Vue.js feature triggers the action 'watch,' a unique feature that allows one to watch a COMPONENT and perform defined ACTIONS when the component's value changes.  

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. 



Discussion

No Comment Found

Related InterviewSolutions