Method vs Computed in Vue

后端 未结 7 542
说谎
说谎 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:48

    Stumbled upon the same question. To me it's more clear like this:

    1. When Vue.js sees the v-on directive followed by a method, it knows exactly which method to call and when to call it.
     // @click
    // method clearMessage is only called on a click on this button
    
    
    /* The method clearMessage is only called on pressing the escape key
    and the alertMessage method on pressing the enter key */
    
    1. When a method is called without the v-on directive it will be called every time an event is triggered on the page that updates the DOM (or simply needs to re-render a part of the page). Even when that method has nothing to do with the event being triggered.

    Uppercase message: {{ messageUppercase() }}

    methods: { messageUppercase() { console.log("messageUpercase"); return this.message.toUpperCase(); } } /* The method `messageUppercase()` is called on every button click, mouse hover or other event that is defined on the page with the `v-on directive`. So every time the page re-renders.*/
    1. A Computed property is only called when a property value is changed that is being referenced by the this word in its function definition.

    Uppercase message: {{ messageUppercase }}

    data() { return { message: "I love Vue.js" } }, computed: { messageUppercase() { console.log("messageUpercase"); return this.message.toUpperCase(); } } /* The computed property messageUppercase is only called when the propery message is changed. Not on other events (clicks, mouse hovers,..) unless of course a specific event changes the value of message. */

    The take away here is that it's best practice to use the computed properties in case a method is not being called with the v-on directive.

提交回复
热议问题