Vue.js calculated attributes

Learn how to use Vue to calculate attribute cache calculations


What are calculated properties

In Vue.js, you can use parentheses to output any data value:

<template>
  <p>{{ count }}</p>
</template>

<script> export default { data() { return { count: 1 } } } </script>

This property can host some small calculations, such as

<template>
  {{ count * 10 }}
</template>

But you can only use one JavaScriptexpression.

In addition to this technical limitation, you also need to consider that the template should only be related to displaying data to the user, and should not perform logical calculations.

To do more with a single expression and have more declarative templates, you can useCalculated attributes.

The calculated properties are incomputedProperties of Vue components:

<script>
export default {
  computed: {

} } </script>

Examples of calculated attributes

This is a sample code using calculated attributescountCalculate the output. note:

  1. I don't need to callcount(). Vue.js automatically calls this function
  2. I used regular functions (instead of arrow functions) to definecountCalculated properties, because I need to be able to access the component instance in the following waythis.

    <template>
    <p>{{ count }}</p>
    </template>
    

    <script> export default { data() { return { items: [1, 2, 3] } }, computed: { count: function() { return 'The count is ’ + this.items.length * 10 } } } </script>

Calculation properties and methods

If you already knowVue method, You may wonder what the difference is.

First, the method must be called, not just the reference method, so you need to callcount()insteadcountIf you have onecountmethod:

<script>
export default {
  data() {
    return {
      items: [1, 2, 3]
    }
  },
  methods: {
    count: function() {
      return 'The count is ' + this.items.length * 10
    }
  }
}
</script>

But the main difference isCalculated attributes are cached.

resultcountThe calculated attributes are cached internally untilitemsData attribute changes.

Important note: The calculated attributes areUpdate only when the reactive source is updated. The regular JavaScript method is not passive, so a common example is to useDate.now():

<template>
  <p>{{ now }}</p>
</template>

<script> export default { computed: { now: function () { return Date.now() } } } </script>

It will render once, and then it will not update even if the component is re-rendered. When the Vue component exits and reinitializes, just refresh the page.

In this case, a method is more suitable for your needs.

Download mine for freeVue manual


More vue tutorials: