The confusion of vue's computed

</script>
        <script>
            new Vue({
                el: "-sharpapp",
                data: function() {
                    return {
                        firstName: "",
                        lastName: "",
                        nickName: ""
                    }
                },
                computed: {
                    name: function() {
                        console.log("computed")
                        if (this.nickName) {
                            return this.nickName
                        } else {
                            return this.firstName + "." + this.lastName
                        }
                    }
                }
            })
        </script>
    </body>
</html>

when nickName has a value, changing firstName or lastName will no longer trigger computed . Can it be understood that the dependency collection of computed changes

when return this.nickname
Mar.23,2021

the first dependency collection occurs when the data data in the component is obtained. In the example above, name in computed collects dependencies according to the program's execution logic.
when your nickName is ', initialization accesses nickName , firstName , and lastName in the component. You can understand that these dependencies are collected, and when they change, the name method is triggered.

when your nickName has a value, only nickName is accessed in initialization. firstName , lastName was not accessed. It can be understood that their dependencies are not collected, so they change and do not trigger the name method. But you should also note that in this case, when nickName is ', the program will access firstName , lastName . Their dependencies will be re-collected here.


when nickName has a value, changing firstName or lastName will no longer return this.firstName +'.'+ this.lastName


generally speaking, it is because vue is smart, he knows that your results remain the same, and you don't have to calculate the specific principle of
again. You can look at the source code


.

this understanding is not correct. Take a look at the if..else.. in your calculation attribute. It is judged that when there is this.nickname, there is no dynamic calculation of the calculation property at all, let alone responsive update, knowing that the computed property is dependent and responsive.

Why not change the code to:

computed: {
    name: function() {
        console.log('computed')
        return this.firstName + '.' + this.lastName
    }
}
Menu