This tutorial helps to understand vuejs computed with examples. The vuejs computed offer you a clear method for extracting new data from attributes that already exist, so you can maintain organized and effective templates.
What’s vuejs computed
Properties that are derived from one or more other properties in Vue.js are called computed properties. vue computed has inbuilt computed()
method that takes a getter function, and the returned value is a computed ref.
if you attempt to assign a new value to a computed property, you will receive a runtime warning. A computed property automatically tracks its reactive dependencies.
Usage of Computed Properties
You can use Vuejs computed properties where you need to derive or transform data based on other reactive data properties. The following are common use cases for computed properties:
- Formatting data for display (e.g., date formatting, currency formatting).
- Filtering or sorting lists based on certain criteria.
- Performing calculations based on input data.
- Conditionally rendering elements based on data state.
Checkout Other vuejs tutorials:
- Implementing Computed Properties in Vue.js
- What Are Vue.js Watchers and How Do They Work?
- Exploring Cookie Management in Vue.js
- How To Get Element by ID in Vue
Simple Example of vuejs computed
Let’s create an example of an employee module in a Vue.js application where we utilize computed properties to calculate the monthly salary of an employee based on their hourly wage and the number of hours worked.
Non-Computed Approach
In this approach, we will calculate the total salary of an employee without using computed properties. Instead, we will manually update the total salary whenever individual salary components change.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Employee Module without Vue.js Computed</title> <!-- Include Vue.js library --> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> </head> <body> <div id="app"> <h1>Employee Module</h1> <!-- Employee Form --> <form @submit.prevent="calculateSalary"> <label for="name">Employee Name:</label> <input type="text" id="name" v-model="employee.name" required><br><br> <label for="hourlyWage">Hourly Wage:</label> <input type="number" id="hourlyWage" v-model.number="employee.hourlyWage" required><br><br> <label for="hoursWorked">Hours Worked:</label> <input type="number" id="hoursWorked" v-model.number="employee.hoursWorked" required><br><br> <button type="submit">Calculate Salary</button> </form> <!-- Display Salary --> <div v-if="employee.monthlySalary !== null"> <h2>Employee Information</h2> <p>Name: {{ employee.name }}</p> <p>Hourly Wage: ${{ employee.hourlyWage }}</p> <p>Hours Worked: {{ employee.hoursWorked }}</p> <h2>Monthly Salary</h2> <p>${{ employee.monthlySalary }}</p> </div> </div> <script> new Vue({ el: '#app', data: { employee: { name: '', hourlyWage: 0, hoursWorked: 0, monthlySalary: null } }, methods: { calculateSalary() { // Calculate monthly salary based on hourly wage and hours worked this.employee.monthlySalary = this.employee.hourlyWage * this.employee.hoursWorked * 4; // Assuming 4 weeks in a month } } }); </script> </body> </html>
Vuejs Computed Approach
We will use computed properties to automatically calculate the total salary whenever any of the salary components change.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Employee Module with Vue.js Computed</title> <!-- Include Vue.js library --> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> </head> <body> <div id="app"> <h1>Employee Module</h1> <!-- Employee Form --> <form @submit.prevent="calculateSalary"> <label for="name">Employee Name:</label> <input type="text" id="name" v-model="employee.name" required><br><br> <label for="hourlyWage">Hourly Wage:</label> <input type="number" id="hourlyWage" v-model.number="employee.hourlyWage" required><br><br> <label for="hoursWorked">Hours Worked:</label> <input type="number" id="hoursWorked" v-model.number="employee.hoursWorked" required><br><br> <button type="submit">Calculate Salary</button> </form> <!-- Display Salary --> <div v-if="employee.monthlySalary !== null"> <h2>Employee Information</h2> <p>Name: {{ employee.name }}</p> <p>Hourly Wage: ${{ employee.hourlyWage }}</p> <p>Hours Worked: {{ employee.hoursWorked }}</p> <h2>Monthly Salary</h2> <p>${{ employee.monthlySalary }}</p> </div> </div> <script> new Vue({ el: '#app', data: { employee: { name: '', hourlyWage: 0, hoursWorked: 0, monthlySalary: null } }, methods: { calculateSalary() { // Calculate monthly salary based on hourly wage and hours worked this.employee.monthlySalary = this.employee.hourlyWage * this.employee.hoursWorked * 4; // Assuming 4 weeks in a month } }, computed: { // Computed property to check if all required fields are filled isFormValid() { return this.employee.name !== '' && this.employee.hourlyWage > 0 && this.employee.hoursWorked > 0; } } }); </script> </body> </html>
in the above code:
Step 1: The user fills out a form with the employee’s name, hourly wage, and hours worked.
Step 2: The calculateSalary method is triggered upon submission of the form. It computes the monthly salary by multiplying the hourly wage by the number of hours worked, based on a monthly assumption of four weeks.
Step 3: The calculated monthly salary is displayed below the form.
Step 4: We have computed the property isFormValid which checks if all required fields are filled. This computed property could be used for form validation or enabling/disabling the submit button based on the form’s validity.
Conclusion
Computed properties in Vue.js are an important feature that makes working with data easier and improves responsiveness in Vue.js apps. You can use compute properties to format data, perform calculations, or conditionally render elements