search
HomeWeb Front-endVue.jsLearn more about computed properties in vue

Learn more about computed properties in vue

Nov 02, 2020 pm 05:53 PM
vueComputed properties

The following Vue.js tutorial column will take you to understand the calculated properties in vue. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Learn more about computed properties in vue

#1. What is a computed attribute

Expressions within templates are very convenient, but they were originally designed to be usedSimple operation. Putting too much logic into a template can make it overweight and difficult to maintain. For example:

<p>
  {{ message.split('').reverse().join('') }}</p>

The expression here contains 3 operations, which is not very clear, so when you encounter complex logic, you should use Vue's special calculated attribute computed to process it.

2. Usage of computed attributes

Various complex logic can be completed in a computed attribute, including operations, function calls, etc., as long as the final return One result will do.

Let’s rewrite the above example using computed properties

<p>
  </p><p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>  //我们把复杂处理放在了计算属性里面了
var vm = new Vue({
    el: '#example',
    data: {
        message: 'Hello'
    },
    computed: {
        reversedMessage: function () {            // `this` 指向 vm 实例
            return this.message.split('').reverse().join('')
        }
    }
});

Result:

Original message: "Hello"

Computed reversed message: "olleH"

In addition to the simple usage in the above example, Computed properties can also rely on the data of multiple Vue instances. As long as any of the data changes, the calculated properties will be re-executed. , the view will also be updated.

    <p>
        <button>补充货物1</button>
        </p><p>总价为:{{price}}</p>
    
var app = new Vue({        
       el: '#app', 
   data: {
       package1: {
           count: 5,
           price: 5
       },
       package2: {
           count: 10,
           price: 10
       }
    },
    computed: {
     price: function(){         return this.package1.count*this.package1.price+this.package2.count*this.package2.price  //总价随着货物或价格的改变会重新计算
     }
    },
    methods: {   //对象的方法
        add: function(){            this.package1.count++
        }
    }
});

There are two very practical tips for calculated properties that are easily overlooked: First, calculated properties can depend on other calculated properties; Second, calculated properties can not only rely on the data of the current Vue instance, but also Depends on the data of other instances, For example:

    <p></p>
    <p>{{ reverseText}}</p>
var app1 = new Vue({
   el: '#app1',
 data: {
      text: 'computed'
    }
});var app2 = new Vue({
    el: '#app2',
    computed: {
        reverseText: function(){
        return app1.text.split('').reverse().join('');  //使用app1的数据进行计算        }
    }
});

Each calculated property contains a getter and a setter. Our two examples above are the default usage of calculated properties. Just use getter to read.

When you need it, you can also provide a setter function. When you manually modify the value of a calculated property just like modifying an ordinary data, the setter function will be triggered to perform some custom operations, such as:

var vm = new Vue({
    el: '#demo',
    data: {
        firstName: 'Foo',
        lastName: 'Bar'
    },
    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];
            }
        }
    }
});//现在再运行 vm.fullName = 'John Doe' 时,setter 会被调用,vm.firstName 和 vm.lastName 也会相应地被更新。

In most cases, we will only use the default getter method to read a calculated property. Setters are rarely used in business, so when declaring a calculated property, you can directly use the default writing method , it is not necessary to declare both getter and setter.

3. Calculated attribute cache

In the above example, in addition to using calculated properties, we can also achieve the same effect by calling methods in expressions, such as :

<p>{{reverseTitle()}}</p>
// 在组件中methods: {
  reverseTitle: function () {    return this.title.split('').reverse().join('')
  }
}

We can define the same function as a method instead of a computed property, and the end result of both ways is indeed exactly the same. Just one uses reverseTitle() to get the value, and the other uses reverseTitle to get the value.

However, the difference is that computed properties are cached based on their dependencies. Computed properties are only re-evaluated when their associated dependencies change.

This means that as long as the title has not changed, accessing the reverseTitle calculated property multiple times will immediately return the previous calculation result without having to execute the function again.

A small example:

        <p>{{reverseTitle}}</p>
        <p>{{reverseTitle1()}}</p>
        <button>补充货物1</button>
        <p>总价为:{{price}}</p>
    computed: {
      reverseTitle: function(){          return this.title.split('').reverse().join('')  //而使用计算属性,只要title没变,页面渲染是不会重新进这里来计算的,而是使用了缓存。
      },
     price: function(){         return this.package1.count*this.package1.price+this.package2.count*this.package2.price
     }
    },
    methods: {   //对象的方法
        add: function(){            this.package1.count++
        },
        reverseTitle1: function(){            return this.title.split('').reverse().join('')  //点击补充货物,也会进这个方法,再次计算。不是刷新,而是只要页面渲染,就会进方法里重新计算。
        }
    },

In contrast, whenever a re-render is triggered, the calling method will always Execute the function again.

Why do we need caching? Suppose we have a computationally expensive property A, which requires traversing a huge array and doing a lot of calculations. Then we might have other computed properties that depend on A.

If there is no cache, we will inevitably execute the getter of A multiple times! If you don't want caching, use methods instead.

Related recommendations:

2020 front-end vue interview questions summary (with answers)

vue tutorial Recommendation: The latest 5 vue.js video tutorial selections in 2020

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of Learn more about computed properties in vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor