In Vue.js, computed properties are properties that are derived from the state of the Vue instance. They are defined using the computed
option in the component's options. Computed properties are cached based on their dependencies, and they only re-evaluate when one of those dependencies changes. This makes them suitable for performing calculations or transformations based on reactive data.
Here's an example of how to use computed properties in Vue.js:
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue.js Computed Properties</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="app">
<p>Original message: {{ message }}</p>
<p>Reversed message: {{ reversedMessage }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
computed: {
// Computed property to reverse the original message
reversedMessage: function () {
return this.message.split('').reverse().join('');
}
}
});
</script>
</body>
</html>
In this example, we have a Vue instance with a message
data property and a computed property called reversedMessage
. The reversedMessage
property is computed based on the message
property – it takes the original message, splits it into an array of characters, reverses the array, and then joins it back into a string. The result is displayed in the template.
When you run this code, you'll see that the "Reversed message" updates automatically whenever you change the original message. Vue.js takes care of efficiently updating the computed property when its dependencies change.
Remember that computed properties should be used for simple computations. If you need to perform more complex logic, you might want to use methods instead. Additionally, keep in mind that computed properties are read-only by default; you cannot directly modify them. If you need to perform two-way binding, you should use v-model
with a custom method or a computed property with a getter and setter.