Vue.js Methods and Computed Properties

In Vue.js, methods and computed properties are essential tools for creating dynamic and reactive user interfaces. They allow developers to define logic that can be reused within the template and manage data more effectively. This chapter will explore methods and computed properties in detail, from basic usage to advanced techniques, with comprehensive examples and explanations.

What are Vue.js Methods and Computed Properties?

Methods

Methods are functions defined within a Vue component that can be invoked in response to user events or other actions. They allow you to encapsulate logic that can be reused throughout your component.

Computed Properties

Computed properties are reactive properties that are evaluated based on their dependencies. They are cached and only re-evaluated when their dependencies change, making them efficient for computed logic that relies on reactive data.

Defining Methods

Basic Method Definition

Methods are defined within the methods option of a Vue instance.

				
					<div id="app">
  <button @click="sayHello">Click me</button>
</div> <script type="litespeed/javascript">new Vue({el:'#app',methods:{sayHello:function(){alert('Hello Vue!')}}})</script> 
				
			

Explanation:

  • methods: { sayHello: function() { ... } } defines a method named sayHello.
  • @click="sayHello" binds the sayHello method to the button’s click event.
  • The output will be an alert displaying “Hello Vue!” when the button is clicked.

Using Methods in Templates

Methods can be called directly from the template, usually in response to events.

				
					<div id="app">
  <input v-model="name">
  <button @click="greet">Greet</button>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{name:'Vue.js'},methods:{greet:function(){alert('Hello '+this.name)}}})</script> 
				
			

Explanation:

  • v-model="name" binds the input value to the name data property.
  • @click="greet" binds the greet method to the button’s click event.
  • The output will be an alert displaying “Hello Vue.js” (or whatever name is entered) when the button is clicked.

Methods with Parameters

Methods can accept parameters, allowing for more dynamic behavior.

				
					<div id="app">
  <button @click="say('Hello', 'Vue.js')">Click me</button>
</div> <script type="litespeed/javascript">new Vue({el:'#app',methods:{say:function(greeting,name){alert(greeting+' '+name)}}})</script> 
				
			

Explanation:

  • say: function(greeting, name) { ... } defines a method that accepts two parameters.
  • @click="say('Hello', 'Vue.js')" calls the say method with the arguments “Hello” and “Vue.js”.
  • The output will be an alert displaying “Hello Vue.js” when the button is clicked.

Common Use Cases for Methods

  • Event handling (e.g., click, submit, hover)
  • AJAX requests and data fetching
  • Form validation and submission
  • Complex calculations that need to be executed multiple times

Defining Computed Properties

Basic Computed Property Definition

Computed properties are defined within the computed option of a Vue instance.

				
					<div id="app">
  <p>{{ reversedMessage }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'Hello Vue.js'},computed:{reversedMessage:function(){return this.message.split('').reverse().join('')}}})</script> 
				
			

Explanation:

  • computed: { reversedMessage: function() { ... } } defines a computed property named reversedMessage.
  • {{ reversedMessage }} binds the reversedMessage computed property to the paragraph element.
  • The output will be “sj.euV olleH”.

Using Computed Properties in Templates

Computed properties are used in templates like regular data properties.

				
					<div id="app">
  <p>{{ fullName }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{firstName:'John',lastName:'Doe'},computed:{fullName:function(){return this.firstName+' '+this.lastName}}})</script> 
				
			

Explanation:

  • fullName: function() { return this.firstName + ' ' + this.lastName; } defines a computed property that combines firstName and lastName.
  • {{ fullName }} binds the fullName computed property to the paragraph element.
  • The output will be “John Doe”.

Computed Properties with Dependencies

Computed properties automatically update when their dependencies change.

				
					<div id="app">
  <input v-model="firstName">
  <input v-model="lastName">
  <p>{{ fullName }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{firstName:'John',lastName:'Doe'},computed:{fullName:function(){return this.firstName+' '+this.lastName}}})</script> 
				
			

Explanation:

  • The fullName computed property depends on firstName and lastName.
  • Updating the input fields will automatically update the fullName output.
  • The output will dynamically change based on the values of firstName and lastName.

Common Use Cases for Computed Properties

  • Data transformation and formatting
  • Combining multiple data properties
  • Deriving new data from existing state
  • Simplifying complex templates by moving logic to computed properties

Computed Properties vs. Methods

Similarities

  • Both can be used to perform logic and return values.
  • Both can be used in templates to display dynamic content.

Differences

  • Caching: Computed properties are cached based on their dependencies and only re-evaluate when their dependencies change. Methods do not cache their results and re-run every time they are called.
  • Usage: Computed properties are primarily used for derived state, while methods are used for actions and events.
				
					<div id="app">
  <p>Computed: {{ computedMessage }}</p>
  <p>Method: {{ methodMessage() }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{message:'Hello Vue!'},computed:{computedMessage:function(){return this.message.split('').reverse().join('')}},methods:{methodMessage:function(){return this.message.split('').reverse().join('')}}})</script> 
				
			

Explanation:

  • computedMessage is a computed property.
  • methodMessage is a method.
  • The output will be the same for both, but the computed property is more efficient due to caching.

Computed Properties vs. Watchers

Computed Properties

  • Purpose: Used for simple reactive calculations and derived state.
  • Efficiency: Cached and re-evaluated only when dependencies change.
  • Usage: Preferred for any reactive data that can be derived from existing state.

Watchers

  • Purpose: Used for performing asynchronous operations, side effects, or complex logic in response to data changes.
  • Efficiency: Executes a callback whenever the watched data changes.
  • Usage: Preferred for handling more complex logic, especially involving asynchronous tasks or side effects.
				
					<div id="app">
  <input v-model="question">
  <p>{{ answer }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{question:'',answer:'I cannot give you an answer until you ask a question!'},watch:{question:function(newQuestion){this.answer='Waiting for you to stop typing...';this.getAnswer()}},methods:{getAnswer:_.debounce(function(){if(this.question.indexOf('?')===-1){this.answer='Questions usually contain a question mark. ;-)';return}
this.answer='Thinking...';var vm=this;axios.get('https://yesno.wtf/api').then(function(response){vm.answer=_.capitalize(response.data.answer)}).catch(function(error){vm.answer='Error! Could not reach the API. '+error})},500)}})</script> 
				
			

Explanation:

  • `watch: { question: function(newQuestion)(newQuestion)  { … } }watches thequestion` property for changes.
  • _.debounce from lodash is used to limit the rate at which getAnswer is invoked.
  • The output will update the answer after a delay when the question contains a question mark.

Advanced Techniques

Caching with Computed Properties

Computed properties are automatically cached based on their dependencies. This caching mechanism improves performance by avoiding unnecessary re-computation.

				
					<div id="app">
  <button @click="incrementCounter">Increment</button>
  <p>Counter: {{ counter }}</p>
  <p>Computed: {{ computedCounter }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{counter:0},computed:{computedCounter:function(){console.log('Computed property evaluated');return this.counter*2}},methods:{incrementCounter:function(){this.counter++}}})</script> 
				
			

Explanation:

  • computedCounter is a computed property that doubles the value of counter.
  • The computed property is only evaluated when counter changes.
  • The console log will show that the computed property is evaluated only when necessary.

Lazy Evaluation

Computed properties are lazily evaluated, meaning they are not computed until their value is needed for rendering or accessing in JavaScript.

				
					<div id="app">
  <button @click="toggleMessage">Toggle Message</button>
  <p v-if="isVisible">{{ expensiveOperation }}</p>
</div> <script type="litespeed/javascript">new Vue({el:'#app',data:{isVisible:!1,dataForExpensiveOperation:[]},computed:{expensiveOperation:function(){console.log('Expensive operation evaluated');return this.dataForExpensiveOperation.map(item=>item.value*2).join(', ')}},methods:{toggleMessage:function(){this.isVisible=!this.isVisible}},created:function(){setTimeout(()=>{this.dataForExpensiveOperation=[{value:1},{value:2},{value:3}]},2000)}})</script> 
				
			

Explanation:

  • expensiveOperation is a computed property that performs an expensive computation on dataForExpensiveOperation.
  • The computed property is evaluated only when isVisible is true and the value is needed for rendering.
  • The console log will show that the expensive operation is evaluated only when the computed property is accessed.

In this chapter, we explored methods and computed properties in Vue.js, fundamental for creating reactive and efficient applications. Methods are used for executing actions and responding to events, while computed properties are ideal for deriving and caching values based on reactive data. Understanding when to use each technique is crucial for optimizing performance and maintaining clean, readable code. By mastering methods and computed properties, you gain powerful tools to handle dynamic behavior and data transformations within your Vue components effectively. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India