E
E
Ewars2017-01-09 10:21:13
Vue.js
Ewars, 2017-01-09 10:21:13

When to use computed and when to use methods in Vue.js? And what is their difference?

I read in the documentation, but did not understand anything. Please explain in simple terms. What is the purpose of each option?
Quote from documentation

Вместо computed property мы можем определить ту же функцию в виде метода. Результат будет одинаковый. Основное отличие в том, что computed property кэшируются на основании значений зависимостей. Computed property будет пересчитано только когда изменится его базовая зависимость. То есть, пока переменная message не менялась, множественные вызовы свойства reversedMessageбудут мгновенно возвращать предварительно полученный результат без очередного запуска функции.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Decadal, 2017-01-09
@ewars

If your function's result doesn't rely on internal data, use methods.
For example, you have a range inside vue that serves as an upper bound for Math.random. If implemented using a method, then each time it will return a new value of Math.random.
The implementation via computed will wait for your range to change, otherwise it will return the same number that was generated the first time
js:

var app = new Vue({
        el: '#content',
        data: {
            range: 1
        },
        computed: {
            rand: function () {
                return Math.random() * this.range ; //ожидалось что app.rand будет давать случайное число
            }
        },
        methods: {
            show: function (event) {
                alert('Случайное число: ' + this.rand); // но нет, число одно и то же
            },
       }
});

html:
<div id="content">
<button v-on:click="show">показать число</button>
</div>

As a result, it will generate the number once and will display it constantly when the button is clicked. If you type app.range = 2; then the generated number will change one-time.
Example for likes mentioned in the comment:
new Vue({
   el: '#content',
   data: {
      likes: 0,
   },
});

<div id="content"><button v-on:click="likes += 1">+1</button></div>

E
Ewars, 2017-01-09
@ewars

Found a good explanation, with an example:
youtube

L
lega, 2017-01-09
@lega

Methods are used to change data, on clicks and events.
computed to output data to the DOM, because vue tracks changes crookedly if output via methods.

Y
Yar-nikita, 2022-02-09
@Yar-nikita

Computed is the same as methods
The only difference is that in methods, the methods must be called manually
And in computed the methods themselves are executed, this is due to changes in variables (which are initialized in data)
For example

new Vue({
   el: '#content',
   data: {
      counter: 0,
   },
   computed: {
   message(){  
        let res = '';
        if(this.counter === 5){
            res = 'Здесь число 5'
       }
        return res
    }
}
});

When the counter is changed, the message method will be automatically executed.
Those who know well that messages in computed are used as variables, I know that I gave such an example because it’s easier to understand, and in practice it’s clear what is where and how.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question