Computed attributes (computed)

Usage scenario: one data, depending on some other data “calculated” results

Computed properties are also variables and therefore cannot have the same name as variables defined in data

Grammar:

    1. Incomplete writing:
computed:{
    "Compute attribute name"() {return "Value"}}Copy the code
    1. Full: “Computed properties are also variables. When you need to assign a value to a computed property, use full.”
    • Set () : this function is automatically triggered when someone “assigns” a value to a calculated property
    • Get () : this function is automatically triggered when someone wants to “use” the value of an attribute variable and returns the value via a return
computed:{
    "Compute attribute name": {set(value){
        // The value received in the set is the calculated value of the property changed
        }
        get(){
            return 'value'}}}Copy the code

Compute the characteristics of attributes

  1. Calculation property used in the variable change, recalculation results returned
  2. Computed attributiveThe cache
    • The calculation properties have a “cache”, where the results of the first calculation are put into memory. On the second use (the value has not changed), the value is used directly (the function is not called)
    • When the value of a variable used in a calculated property changes, it is recalculated and cached

The calculated properties are cached according to the results of dependent variables, and the recalculated results are stored in the cache depending on the change, which has higher performance than ordinary methods

<template>
    <div>
        <div>{{num}}</div>
        <div>{{num}}</div>
        <div>{{num}}</div>
    <div>
</template>

<script>
    export default {
        computed: {num(){
                   console.log('Compute properties')// Print only once
                   return 123}}}</script>
Copy the code

The listener (watch)

Function: Listens for data/computed property values to change syntax:

  • Listen for common properties:
    • NewVal: receives the value of the listened property changed
    • OldVal: Receives the value before the monitored property changes
"Properties to be listened on"(newVal,oldVal){
    / / code
    // Change the value of the variable name automatically
}
Copy the code
  • Listen for complex properties:
    • Usage scenario: variable is stored in the address of the object in the heap memory, bidirectional binding modification, change is the value of the attribute in the object, but the object itself does not change, only the use of depth monitoring can monitor the internal changes of the object.
"Properties to be listened on": {deep:true.// Enable deep listening to listen for changes within complex types
    handler (newVal, oldVal) {
          / / code
          // Change the value of the variable name automatically}}Copy the code