Vue basis (calculated attribute)

In the template, you can directly display some data in the data through the interpolation syntax. In some cases, we need to convert the data or display it after calculation. We can use the calculated option to calculate. At this time, some partners may ask, why should I define the function directly and call it again? This problem will be explained below. Let's take a look at how to use calculation attributes first!

Splice name case

<template>
  <div id="app">
    <!-- Original splicing method -->
    <p>{{ fastName }} {{ lastName }}</p>
    <!-- Calculation in template syntax -->
    <p>{{ fastName + " " + lastName }}</p>
    <!-- Call function calculation -->
    <p v-text="fullName2()"></p>
    <!-- Calculate using calculation properties -->
    <p>{{ fullName1 }}</p>
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      fastName: "Tracy",
      lastName: "McGrady",
    };
  },
  computed: {
    fullName1: function () {
      return this.fastName + " " + this.lastName;
    },
  },
  methods: {
    fullName2: function () {
      return this.fastName + " " + this.lastName;
    },
  },
};
</script>

Operation results:

Shopping cart price statistics case

<template>
  <div id="app">
    <p>{{ totalPrice }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      bookes: [
        { id: 100, name: "Unix Programming art", price: 119 },
        { id: 200, name: "Java Programming thought", price: 105 },
        { id: 300, name: "High concurrency programming", price: 98 },
        { id: 400, name: "Spring5", price: 99 },
      ],
    };
  },

  computed: {
    totalPrice: function () {
      let result = 0;
      // Ordinary cycle
      /* for(let i = 0;i < this.bookes.length;i++){
            result += this.bookes[i].price;
          } */

      // Enhanced for loop with i as index
      /* for(let i in this.bookes){
            result += this.bookes[i].price;
          } */
      // ES6 adds a for loop to get objects directly
      for (let book of this.bookes) {
        result += book.price;
      }
      return result;
    },
  },
};
</script>

The running result is the price of the commodity displayed on the browser: 421

The above two cases are for you to practice and experience the usage of computing attributes. What is its principle? How? What's the difference between him and me defining function calls?

In fact, the complete writing method of calculating the attribute includes getter and setter methods and declares a fullName object. Because we generally only get the value, we will omit it and write it as the above case. We will call the get method when obtaining data and the set method when setting data.
Objective: the calculation attribute is also a variable. If you want to assign a value directly, you need to use the complete writing method
Syntax:

computed: {
    "Attribute name": {
        set(value){
            
        },
        get() {
            return "value"
        }
    }
}

Requirements:

  • Calculate properties for v-model
    Page preparation input box
<template>
  <div>
      <div>
          <span>full name:</span>
          <input type="text" v-model="full">
      </div>
  </div>
</template>
<script>
// Problem: assign a value to a calculated property - setter required
// solve:
/*
    Full syntax:
    computed: {
        "Calculated property name '() {},
        "Calculated attribute name:{
            set(Value){

            },
            get(){
                return value
            }
        }
    }
*/
export default {
    computed: {
        full: {
            // Assigning a value to full triggers the set method
            set(val){
                console.log(val)
            },
            // Trigger the get method with the value of full
            get(){
                return "anonymous person"
            }
        }
    }
}
</script>
<style>

</style>

Summary: to assign a value to a calculated attribute, you need to use the set method

Case - small selection affects all selection
Objective: select all the small boxes (manually), and select all automatically

  • Requirement: select all the small boxes (manually), and select all automatically

analysis:
① First static and then dynamic, get static labels and data from. md
② Generate check boxes and text circularly, the c attribute of the object and the selected state of the small selection box, and bind them Bi directionally with v-model
③ Define the isAll calculation attribute. The value is obtained by counting the c attribute status through the small selection boxes

<template>
  <div>
    <span>Select all:</span>
    <!-- 4. v-model Associate select all - Selected status -->
    <input type="checkbox" v-model="isAll" />
    <button @click="btn">Reverse selection</button>
    <ul>
      <li v-for="(obj, index) in arr" :key="index">
        <!-- 3. object.c - Association selected status -->
        <input type="checkbox" v-model="obj.c" />
        <span>{{ obj.name }}</span>
      </li>
    </ul>
  </div>
</template>
<script>
// Target: small selection box - > select all
// 1. Label + style + js ready
// 2. Display the data cycle on the page
export default {
  data() {
    return {
      arr: [
        {
          name: "Zhu Bajie",
          c: false,
        },
        {
          name: "Sun WuKong",
          c: false,
        },
        {
          name: "Tang Monk",
          c: false,
        },
        {
          name: "White dragon horse",
          c: false,
        },
      ],
    };
  },
  // 5. Calculate attribute - isAll
  computed: {
    isAll: {
      set(val) {
        // 7. Select all box - selected (true/false)
        this.arr.forEach((obj) => (obj.c = val));
      },
      get() {
        // 6. Statistics of small box status - > select all status
        // every formula: find the "unqualified" condition in the array and return false directly in place
        return this.arr.every((obj) => obj.c === true);
      },
    },
  },
  methods: {
    btn() {
      // 8. Reverse the c attribute of the object in the array and give it back
      this.arr.forEach((obj) => (obj.c = !obj.c));
    },
  },
};
</script>

Compute attribute cache
For the difference between methods and computed, the following code uses interpolation syntax, methods and calculation attributes to render data respectively.

<template>
  <div>
    <!-- The original method, which is cumbersome in data calculation, is not recommended -->
    <p>name:{{ name }} Work:{{ job }}</p>
    <!-- methods The function is called every time the data is obtained -->
    <p>{{ getInfo1() }}</p>
    <p>{{ getInfo1() }}</p>
    <p>{{ getInfo1() }}</p>
    <p>{{ getInfo1() }}</p>
    <!-- computed When the data does not change, it is called only once to cache the data -->
    <p>{{ getInfo2 }}</p>
    <p>{{ getInfo2 }}</p>
    <p>{{ getInfo2 }}</p>
    <p>{{ getInfo2 }}</p>
    <p>{{ getInfo2 }}</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: "McGrady",
      job: "NBA ball-game star",
    };
  },

  methods: {
    getInfo1: function () {
      console.log("methods");
      return "name:" + this.name + "Work:" + this.job;
    },
  },

  computed: {
    getInfo2: function () {
      console.log("computed");
      return "name:" + this.name + "Work:" + this.job;
    },
  },
};
</script>

<style>
</style>


1) , methods and computed all seem to implement our functions
2) . the calculated attribute will be cached. If it is used multiple times, the calculated attribute will only be called once

Tags: Javascript Front-end Vue Vue.js

Posted on Fri, 03 Dec 2021 17:52:10 -0500 by pbaker