Vue about computed calculation properties?

Why did Vue console computed, once and methods? three times?
Code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./vue.js">

    </script>
</head>

<body>
    <div id="app">
        <span>
            {{computedMessage}}
            {{computedMessage}}
            {{computedMessage}}
        </span>
        <span>
            {{calcMessage()}}
            {{calcMessage()}}
            {{calcMessage()}}
        </span>
    </div>
    <script>
        var app = new Vue({
            el: "-sharpapp",
            data: {
                message: "hi"
            },
            computed: {
                computedMessage() {
                    console.log("computed")
                    return "computed " + this.message
                },
            },
            methods: {
                calcMessage() {
                    console.log("methods")
                    return "calc " + this.message
                }
            }
        })
    </script>
</body>

</html>
Jun.20,2021

official explanation ide/computed.html-sharp%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%E7%BC%93%E5%AD%98-vs-%E6%96%B9%E6%B3%95" rel=" nofollow noreferrer "> https://cn.vuejs.org/v2/guide.

// 
methods: {
  reversedMessage: function () {
    return this.message.split('').reverse().join('')
  }
}

We can define the same function as a method rather than a calculation property. The end result of the two approaches is indeed exactly the same. The difference, however, is that calculated properties are cached based on their dependencies. They are re-evaluated only when the relevant dependencies change. This means that as long as the message has not changed, multiple visits to the reversedMessage calculation property will immediately return the previous calculation results without having to execute the function again.


calculating attributes computed is based on its dependency, that is, the above method of calculating attributes computedMessage () depends on message , so computedMessage () only runs once, so it is output only once. bold message before and after each visit computedMessage is the result of the previous cache, while in methods You directly called it three times in the code, so you output three times


although what is said above is true, the only reason here is that computedMessage has only been evaluated once, that is, a get operation has been triggered by the template after computed initialization.


the result of the calculated property is cached and is recalculated unless the dependent responsive property changes. Note that if a dependency (such as a non-responsive property) is outside the scope of the instance, the calculated property is not updated.

Menu