[Vue] Basic (Data & Calculation Properties & Methods)

Let's start with an example

<template>
  <div>
    <p>source array:{{numbers}}</p>
    <p>sorted array:{{sortArray()}}</p>
    <p>3 in array index : {{findIndex(3)}}</p>
    <p>totalNumbers : {{totalNumbers}}</p>
    <button @click="changeArray()">修改数组</button>
  </div>
</template>

<script>
export default {
  data() {
    return { numbers: [1, 5, 3, 9, 2, 4, 8] };
  },
  computed: {
    totalNumbers() {
      console.log("compute total");
      return this.numbers.reduce((total, val) => total + val);
    }
  },
  methods: {
    sortArray() {
      return this.numbers.slice(0).sort((a, b) => a - b);
    },
    findIndex(value) {
      console.log("find index");
      return this.numbers.findIndex(m => m === value);
    },
    changeArray() {
      for (let i = 0; i < this.numbers.length; i++) {
        this.$set(this.numbers, i, Math.floor(Math.random() * 100));
      }
    }
  }
};
</script>

 running result

 

1. First define a set of arrays (data)
2. Define calculated attributes, calculate the sum of arrays (calculated attributes)
3. Define 3 methods, sort arrays, find subscripts of specified values, modify arrays (methods)

 

data

The data object is best for pure data: if you want to put the data somewhere, then use it in templates, methods or calculated properties

 

Calculated attribute

Computed properties are suitable for performing more complex expressions, which are often too long or need to be reused frequently

The calculated attribute will be cached, and the dependent data will not be changed. It will be taken directly from the cache. This can be printed in console.log, and the calculated attribute can be verified. Therefore, the calculation attribute is suitable for intensive CPU calculation.

Calculation properties can be set to read and write

total:{
    get(){
        ....
    }
    set(){
        ...
    }
}

 

method

If you want to add a function to the template, it is best to use a method, usually passing parameters and getting different results based on the parameters.


 

data object vs method vs calculated attribute

  Readable Writable Accept parameters Need calculation Cache
data Yes Yes Can't no no
method Yes no can Yes no
Calculated attribute Yes Yes no Yes Yes

Guess you like

Origin www.cnblogs.com/WilsonPan/p/12755476.html