format_list_bulleted
[Vue.js] Explanation of how to write and use the 【vue watch】 property.
最終更新日時:2022-06-30 02:18:09



When using Vue, there are times when you need to monitor and process data changes. This section describes Vue's watch property, which is useful in such situations.

What is Vue watch property?

The watch property can be used when you need to monitor data changes and trigger asynchronous or complex processing.

How to use Vue watch property

Let's take a look at how to write a watch property.

How to write Vue watch property

In the watch property, you can write the following to trigger a change in a monitored variable.

タイトル:main.js

watch: {
   Describe the name of the property to watch for changes: function (value after change[, value before change]) {
      Describe the process here
 }
}

And when setting options, write the following (each option is false by default)

  • deep(optional) : If true, changes to nested values are also detected if the property being monitored is an object. This is covered in detail in "Monitoring Objects".
  • immediate(optional) : If true, also called on initial read.

タイトル:main.js

watch: {
   describe the name of the property to watch for changes: {
     handler: function (value after change, value before change) {
       //Write the process
   }
     [deep: boolean,]
     [immediate: boolean,]
 }
}

In this way, deep and immediate are represented by object keys and boolean values, respectively, and the callback function is described by a handler.


The immediate option is important when using props, for example, because it allows you to apply changes at mount time in props and thus accommodate changes in the value of the parent. For example, the following code is a good example of this: If you want to know more about props, please refer to 「Vueのpropsの書き方・使い方について解説」!

タイトル:main.js

Vue.component('parent', {
   data: function () {
       return {
           name: "Code-Database"
       }
   },
   template: `
   <div>
   <input type="text" v-model='name'/>
   <child :person=name></child>
   </div>`
})

Vue.component('child', {
   props: ['person'],
   data: function () {
       return {
           greeting: ""
       }
   },
   watch: {
       person: {
           immediate: true,
           handler: function () {
               this.greeting = "hello! " + this.person
           }
       }
   },
   template: '<div>{{ greeting }}</div>'
})

new Vue({
   el: "#sample",
})

If immediate is false or unspecified, the person change is not applied during initial component loading and the greeting will be an empty string. However, by setting immediate to true, the greeting will be loaded as hello! Code-Database from the initial loading as if it were a computed property.

When monitoring objects (Objects)

If the value to be monitored is an object, the addition or deletion of an object will be detected, but changes in the value of each property within the object will not be detected. For example, consider the following code.

タイトル:main.js

new Vue({
   el: "#sample",
   data: {
       obj: {
           value: ""
       }
   },
   watch: {
       obj: function () {
           //Write the process
       }
   },
})

In such a program, when there is a change in the value of a value, watch cannot detect the change. In such a case, use the DEEP: TRUE option described in the previous section. It can also be handled by writing the value of the object separately. For example, in the above code, watch can be applied to value as well by doing the following.

タイトル:main.js

new Vue({
   el: "#sample",
   data: {
       obj: {
           value: ""
       }
   },
   watch: {
       obj.value: function () {
           //Write the process
       }
   },
})

Example implementation of Vue's watch property

Let's consider an asynchronous call to an API that returns advice according to a selected number. To do so, we declare the watch property as follows

タイトル:index.html

<div id="example">
  <p>
    Choose advice number(1~217):
    <input v-model="answer">
  </p>
  <p>new advice: {{ newAdvice }}</p>
  <p>old advice: {{ oldAdvice }}</p>
</div>

タイトル:vue.html

<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script>
var vm = new Vue({
  el: '#example',
  data: {
    oldAdvice: '',
    newAdvice: '',
    answer: ''
  },
  watch: {    // API access to answer changes
    answer: function () {
      this.newAdvice = 'Loading...' //Temporarily displayed until API results are returned
      var vm = this
      var number = this.answer
      axios.get('https://api.adviceslip.com/advice/' + number)
        .then(function (response) {
          vm.newAdvice = response.data.slip.advice + ' ('+ number + ')'
        })
        .catch(function (response) {
          vm.newAdvice = 'Could not get the reponse from the API.'
        })
    },    //API access according to newAdvice changes
    newAdvice: function (newData, oldData) {      //Exclude non-advice items displayed in newAdvice
      if(oldData !== 'Loading...' && oldData !== 'Could not get the reponse from the API.'){
        this.oldAdvice = oldData
      }
    }
  },
})
</script>

In this way, the api can be accessed each time an input field is changed. A more specific process is as follows.

Monitor answer changes

  • Asynchronous processing (API access)
  • Display different values until the result is returned from the API

Monitor newAdvice changes

  • Assign the original data of newAdvice to oldAdvice

Difference between WATCH and COMPUTED properties

A similar property is the computed property (arithmetic property), which is more appropriate when the computed property can be used because it can be described concisely. However, the watch property is useful for more complex and generic processing, such as asynchronous communication access as described above. The following is a list of cases where the watch property should be used.

  • For complex processing such as asynchronous communication that cannot be handled by the computed property. (see the concrete example at the end of the previous section.)
  • When using before and after update values
  • If the process executes but does not return data

Also, the following is a comparison of the amount of description for the watch property and the computed property.

Let us consider the case where the resultNum is the value obtained by multiplying firstNum and secondNum.

For the WATCH property

タイトル:app.js

var vm = new Vue({
 el: '#example',
 data: {
   firstNum: 3,
   secondNum: 4,
   resultNum: 12,
 },
 watch: {
   firstNum: function (val) {
     // `this` points to a vm instance
     this.resultNum = val * this.secondNum;
   },
   secondNum: function (val) {
     this.resultNum = this.firstNum * val;
   }
 }
})

For the computed property

タイトル:app.js

var vm = new Vue({
  el: '#example',
  data: {
    firstNum:3,
    secondNum:4
  },
  computed: {
    // Calculation getter function
   resultNum: function () {
      // `this` points to a vm instance
      return this.firstNum * this.secondNum
    }
  }
})

Thus, the code written with the computed property is more concise and highly readable. Therefore, it is recommended that the computed property be used when it is possible to use the computed property.

Summary of this article

This article introduced Vue's watch property (monitoring property)!

Finally, let's summarize the main points of the article.

  • Use the watch property when you want to perform some processing triggered by data changes.
  • The contents to be processed are indicated in several ways in the WATCH property.
  • Compared to the computed property, the description is more verbose, but there are some asynchronous or complex processes that can only be realized with the WATCH property.

We'll definitely take advantage of Vue's watch property!