Computed

27 Dec 2023 . vue .

computed Vs method

<div id="app">
    <h2></h2>
    <h2></h2>
    <h2></h2>
    <h2></h2>
    <h2></h2>
    <h2></h2>
    <h2></h2>
    <h2></h2>
  </div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el:"#app",
      data:{
        firstName:"skt t1",
        lastName:"faker"
      },
      computed: {
        fullName(){
          return this.firstName + " " + this.lastName
        }
      },
      methods: {
        getFullName(){
          return this.firstName + " " + this.lastName
        }
      },
    })
  </script>

Computed property has cache. When this.firstName + " " + this.lastName stays unchanged, method calls 4 times and computed only calls once. When firstName changes, computed calls once but method still calls 4 times.

The computed attribute is within the Vue instance. Modifying object ouside Vue instance will not cause rendering. However, if you modify the object of the Vue computed attribute, external object will be rerendered.

computed Vs watch

computed: {
  total() {
    return this.price * this.quantity;
  }
}

watch: {
  quantity(val) {
    this.total = this.price * val;
  },
  price(val) {
    this.total = this.quantity * val;
  }
}

A watcher is basically a function that Vue automatically executes when the watched property changes. We would have to add a third watcher if the total property also depended on the tax. This is the main reason why it’s a better idea to use a computed property instead.

Watchers are more powerful and allow us to perform complex operations such as HTTP calls or execute some asynchronous logic that wouldn’t be possible with a computed property.

export default {
  data() {
    return {
      actorId: null,
      movies: [],
    };
  },
  methods: {
    getMovies() {
      // http request
      axios.get(`movies/actor/${this.actorId}`)
      .then(resp => {
        this.movies = resp.data;
      });
    }
  },
  watch: {
    actorId(val) {
      if(val) this.getMovies();
    }
  }
}

Another use case for a watcher is when we need to watch a data property until it reaches a specific value, and only then do something.

watch: {
  quantity(val) {
    if (val > this.stock) {
      this.error = true;
      this.errorMessage = `We only have ${this.stock} units`;
    }
  },
}