Vue.Js Computed And Watcher Properties


Vue.Js Computed And Watcher Properties:–In earlier tutorials we have already seen the templates and their rendering in DOM structure very well. But now we will learn about computed properties. We will study the following topic and concepts?
What are computed and watcher properties and where and how do we use them in our application?

We will cover both topics one by one in detail. First we come across computed property. So let you know about the computed property.

Vue.Js Computed Property | Example

You have oftenly seen that we can bind javascript data properties in a template directly by using string interpolation approach. Therefore we need not to call property on data object explicity. Vue.Js does itself this operation for us.

But here comes a serious problem itself when we need to execute more complex logic like looping using interpolation to bind with template. So it is recommended not to use any loop or complex data operation in template interpolation. To avoid this problem in order to maintain our code easily Vue.Js provide us computed property.

Converting Javascript Object into Template Without Computed Property | Example

Here we are going to discuss only about the scenario where you can see only interpolation concept to access javascript data object’s properties.

In example we write a code to reverse the message value. See the example how does the changes take place.

Example

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
</head>
<body>
<div id="app">
  {{ message.split('').reverse().join('') }}
</div>
<script>
  var vm = new Vue({
  el: '#app',
  data: {
  message: 'Tutorialsplane'
  },
   
  methods: {
    button_click: function (event) {
      alert('Hello ' + this.message + '!')
      if (event) {
        alert(event.target.tagName)
      }
    }
  }
})
</script>
</body>
</html>

Converting Javascript Object into template With Computed Property | Example

By using comp property approach makes it pretty neat and concise method to make any change in data property.

Here we have used {{ reversedMessage }} interpolation notation to reverse the “message”.

Example

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
</head>
<body>
<div id="app">
  <button v-on:click="button_click">click</button>
  {{ reversedMessage }}
</div>
<script>
  var vm = new Vue({
  el: '#app',
  data: {
  message: 'Tutorialsplane'
  },
   
  methods: {
    button_click: function (event) {
      alert('Hello ' + this.message + '!')
      if (event) {
        alert(event.target.tagName)
      }
    }
  },
  computed: {
    // a computed getter
    reversedMessage: function () {
      // `this` points to the vm instance
      return this.message.split('').reverse().join('')
    }
  }
    
})
</script>
</body>
</html>

Computed Caching Vs Methods

1.In above example we can bind the message property by using method declaration instead of computed propertyreversedMessage. But computed property has a unique feature cashing which methods don’t provide.You know cashing is a more powerful principle of any operation in programming which helps a programmer in many ways.

2.In general computed properties provide caching which in turn works efficiently than a method approach in program.

3.In other words you can reach by the term uncaching means extraneous work done by the program which reduces performance for the program.

4.So we recommend you to write computed propert only when they are needed.

5.So computed property fetches ole evaluated data and returns it each time until no change is seen in data object.

6.A computed property re-evaluate itself only if data property got changed using dependency updation.

7.Below example is the beast suitable example of computed property where we are cashing the date in our program.

computed: {
  now: function () {
    return Date.now()
  }
}

Computed Getters And Setters | Example

Computed property provide getters and setters facility to set and get data properties according your program’s need. Below we are giving an example which has two data properties namedfirstName and which are initially printed on browser screen as shown in first screenshot. But you set their values manually by using your program’s console. Just go to the console and type vm.fullName=”John Brandy” then immediately your output screen will get changes and you will get output as shown in second screenshot below.

Example

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
</head>
<body>
<div id="app">
  <button v-on:click="button_click">click</button><br />
<p>FirstName:: {{ firstName }}</p>
<p>LastName:: {{ lastName }}</p>
 <p>FullName::{{ fullName }}</p>
</div>
<script>
  var vm = new Vue({
  el: '#app',
  data: {
  message: 'Tutorialsplane',
   firstName: 'John ',
   lastName: 'Brandy'
  },
   
  methods: {
    button_click: function (event) {
      alert('Hello ' + this.message + '!')
      if (event) {
        alert(event.target.tagName)
      }
    }
  },
  computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}   
})
</script>
</body>
</html>

Watchers | Example

Watchers are used in such scenarios where data changes quickly. In below example we use a javascript object named Question. To see the change in value we have used v-model directive. When a user types something in input textbox ; immediately alert comes up after notifying the change in old value(i.e null initially) and hence this work is done by watcher property as we have seen in above program.

Example

<html>
    <head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
    </head>
    <body>
<div id="app">
 <input type="text" v-model="searchQuery"/>
  {{ searchQuery }}
</div>
<script>
  var vm = new Vue({
  el: '#app',
  data: {
  message:'The Tutorialsplane is the best and largest web development tutorials website',
  ans:true,
  searchQuery:'',
  games: [
      'Clash Royale',
      'Pokeman Go',
      'Dead Trigger 2',
      'Minecraft'
    ],
  },
   methods: {
    reverseTemplate: function () {
      this.message = this.message.split('').reverse().join('')
    }
  },
   watch:{
    searchQuery:function(newValue, oldValue){
       console.log("watch called")
       alert('Counter changed from ' + oldValue + ' to ' + newValue + '!')
  }
  }   
})
</script>
</body>
</html>

Try it »


Advertisements

Add Comment

đź“– Read More