Method vs Computed in Vue

后端 未结 7 460
说谎
说谎 2020-11-28 01:00

What is the main difference between a method and a computed value in Vue.js?

They look the same and interchangeable.

相关标签:
7条回答
  • 2020-11-28 01:53

    One of difference between computed and method. Suppose we have a function which will return counter value.(counter is just variable). Let's look how function behaves in both computed and method

    Computed

    At first time of execution the code inside the function will be executed and vuejs will store the counter value in cache(for accessing faster). But when we are again calling the function vuejs will not again execute the code written inside of that function. It first checks any changes made to the counter or not. If any changes made then only it will re-execute the code which is inside that function. If there are no changes made to the counter vuejs will not again execute the function. It will simply return the previous result from the cache.

    Method

    This is just like a normal method in the javascript. Whenever we call the method it will always execute the code inside the function irrespective of changes made to the counter.

    Method will always reexecutes the code irrespective of changes in the code. where as computed will reexecute the code then only if one of it's dependency's values changed. Otherwise it will give us the previous result from the cache without reexecuting

    0 讨论(0)
提交回复
热议问题