SoFunction
Updated on 2025-04-05

Computed computed understanding of computed attributes in vue includes the difference between vue listener, cache and computed

1. Computed properties

1. vue computed description

When some data needs to be changed according to other data, it needs to be processed before it can be displayed. Although vue provides a way to bind data expression binding, its original intention is only for simple operations. Putting too much logic into the template will make the template too heavy and difficult to maintain. It may be too complicated and special calculations, and writing the calculation properties in the template is not conducive to project maintenance

The main functions of computered:

Separation logic (template and data separation)

Cache value

Two-way binding (getter,setter)

2. Syntax format

Format

computed:{ [key: string]: Function | { get: Function, set: Function } }

Parameter description:

key: string type

Value: can be a method. If it is a method, it is a get operation by default, or it can be an object. Set the get attribute or set attribute

3. Basic usage

illustrate

Various complex logic can be completed in a computed property, including operations, function calls, etc., and finally a result is returned.

Computed attributes can also rely on data from multiple Vue instances. As long as any of the data changes, computed attributes will be re-executeed and the view will be updated. This applies toTime-consumingData calculation

Sample code

<div >
    <!--How to use expressions-->
    <p v-text="originalPrice - discountPrice"></p>
    <!--How to use computed properties-->
    <p v-text="currentPrice"></p>
</div>
<script src="/npm/vue/dist/"></script>
<script>
    let app = new Vue({
        el: '#app',
        data: {
             id:1,
            originalPrice:1200,
            discountPrice:200,
        },
        //Calculate properties        computed: {
            // Change date to strings in common specification formats.            currentPrice: function () {
                return "Current Price:" + ( - );
            }
        }
    });

4. Setter and getter

illustrate

Each computed attribute contains onegetterAnd onesetter, the above examples are all the default usage of computed attributes, but they are usedgetterCome to read

If necessary, you can also provide asetterFunction, when modifying the value of a calculated property is like modifying a normal data, it will triggersetterFunction

Sample code

<div >
    <p v-text="currentPrice"></p>
</div>
<script src="/npm/vue/dist/"></script>
<script>
    let app = new Vue({
        el: '#app',
        data: {
            id: 1,
            originalPrice: 1200,
            discountPrice: 200,
        },
        //Calculate properties        computed: {
             cache:false,
            // Change date to strings in common specification formats.            currentPrice: {
                get: function () {
                    return "Current Price:" + ( - );
                },
                // Note that parameters must be passed, otherwise it will be meaningless                set: function (value) { 
                    //Perform a custom operation                     = value
                }
            }
        }
    });
</script>
<!-- 
exist console middle enter =300 
1> Execute firstgetMethod changesdiscountPriceValue of
2> Because the data has changed So the current price will be recalculated, implementgetmethod
-->

Notice

In most cases, we will only use the default onegetterMethods to read a computed attribute are rarely used in businesssetter, so when declaring a computed attribute, you can directly use the default writing method

5. Cache

illustrate

Computational properties are cached based on their dependencies and will only be re-evaluated when the relevant dependencies change. Generally, responsive dependencies

What is responsive dependency? VueCannot detect the addition or deletion of object properties. Since Vue will execute properties when initializing the instancegetter/setterThe transformation process, so the attribute must bedataOnly when an object exists, Vue can convert it so that it can be responsive.

Sample code

<!-- Responsive dependencies -->
<script>
    var vm = new Vue({
      data: {
        // Declare message as an empty string        message: ''
      },
    })
    // Responsive     = 'Hello!'

    ="Non-responsive value"
</script>

 

<div >
    <button @click="getMethodsDate">methods</button>
    <button @click="getComputedDate">computedWith cache</button>
</div>
<script src="/npm/vue/dist/"></script>
<script type="text/javascript">
    new Vue({
        el: '#app',
        methods: {
            getMethodsDate: function () {
                (new Date().toLocaleTimeString())
            },
            // Return the computed attribute set in the computed option - computedDate            getComputedDate: function () {
                ("Cache--->" + )
            }
        },
        computed: {
            computedDate: function () {
                return new Date().toLocaleTimeString()
            }
        }
    })
</script>

6. The difference from methods

computed Only when computed is met: if dependent data exists and dependent data changes these two conditions, computed will be recalculated. The data under methods is calculated every time

The call method is different.computedThe defined members are accessed like attributes, andmethodsThe defined members must be called as a function.

computedis cached and will only be recalculated if the responsive attributes it references change, andmethodsThe functions in it must be executed every time they are called.

5. Listener (watch)

1. Description

Official: This method is most useful when it is necessary to perform asynchronous or overhead operations when data changes. The watch option allows us to perform asynchronous operations (access an API), limits the frequency of the operation, and sets the intermediate state before we get the final result.

watchAnd what we introduced earliermethodsSame syntax, but there is a key difference. Although the value of a nested property is indeed a function, the name of the key must correspond to the name in the data property

2. Syntax format

watch:{
[key: string]: string | Function | Object }]

3. Syntax description

key: Must be a property defined in Vue object data

Value: The value can be a string, which is the method name; the value can be a function; the value can be an object, which contains callback functions and other options: such as whether to traverse in depth.

4. Basic use

Sample code

<script src="/npm/vue/dist/"></script>

<script>
    let vm = new Vue({
        data: {
            test: "111",
            user: {
                name: "Master Emperor",
                address: {
                    city: "Big Wuhan"
                }
            }
        },
        methods: {
            fun: function (val) {
                alert(val)
            }
        },
        watch: {
            // Method name corresponding to the function name in methods            // test: 'fun',
            // Function method            test: function (v1, v2) {
                alert("New Value" + v1 + "====Old value:" + v2)
            },
            /**
              *What is depth, for example data: {test: "111", user: {name: "Madi", address{city:'Big Wuhan'}}
              * The corresponding value of the user attribute is deep, and it is pushed in one go
              * If the user attribute we listen to when the property changes, watch monitoring will not be available, all we need to use deep monitoring here
              */
            //
            user: {
                handler: function (val) {
                    alert()
                },
                // Whether to listen in depth, default is false                // If not set to true, when we manually set = "Ludi", it will not be monitored                deep: true
            },
            /**
              * Or you can also use the following method to monitor
              * Note that the key value must be a string, so enclose it in quotes
              *
              */

            "": function (val) {
                alert(val)
            }
        }
    });
     = '333';
     = "Ludi";
     = 'Changsha'

 

<div >
    <input type="text" v-model="search"/>
    <ul>
        <li v-for="result in results" v-text="result"></li>
    </ul>
</div>
<script src="/npm/vue/dist/"></script>

<script>
    let vm = new Vue({
        el: "#app",
        data: {
            user:{
                name:"Master Emperor",
            }
            search: "",
            results: [],
            
        },
        methods: {
          fun: function () {
            alert("111");
          }
        }
        watch: {
         //Use functions            search: function (v1, v2) {
             ('New value: %s, Old value: %s', v1, v2)
                (v1)
            }
        }
        
    })
</script>

5. The difference between computed

Different trigger conditions

The computed computed attribute will depend on the data attribute that uses it. As long as the value of the dependent data attribute changes, the custom call to the computed attribute will be executed once.

Watch will automatically call the watch callback function when the monitored data attribute value changes.

Different application scenarios

Perform asynchronous operations, expensive operations to avoid blocking the main thread, and use watch.

Simple and serially returned, using computed

More aboutVUE calculation attribute computedFor related articles, please check the relevant links below