In Vue.js, computed properties are a highly beneficial feature, particularly ideal for handling complex data logic. They cache results based on dependencies and recalculate only when those dependencies change, making them more efficient than methods—especially for repetitive calculations requiring performance optimization.
Practical Example of Computed Properties:
Consider developing an e-commerce website where you need to display the price and discount information for each product in the product list interface. You have base product prices but must calculate the discounted price. Here, computed properties can achieve this efficiently.
vue<template> <div> <h2>商品列表</h2> <ul> <li v-for="product in products" :key="product.id"> {{ product.name }} - Original Price: {{ product.price }} - Discounted Price: {{ product.discountedPrice }} </li> </ul> </div> </template> <script> export default { data() { return { products: [ { id: 1, name: '手机', price: 2999, discount: 0.8 }, { id: 2, name: '平板', price: 4999, discount: 0.75 } ] }; }, computed: { productsWithDiscount() { return this.products.map(product => ({ ...product, discountedPrice: (product.price * product.discount).toFixed(2) })); } } } </script>
In this example, productsWithDiscount is defined within the computed properties. It calculates the discounted price for each product based on the products array. This computed property automatically caches results and recalculates only when the products array changes—such as when prices or discount rates vary—thereby improving efficiency.
By doing this, you maintain the immutability of the original data while providing derived data for the interface, ensuring data consistency and reducing unnecessary computations and resource consumption.