[Vuejs]-Vue computed property functions are never called

1๐Ÿ‘

โœ…

As Phil says, "Computed property functions are not meant to alter any data properties and are supposed to return a value". Is because computed watchs changes only in return, for example:

//Computed watch this
return this.a + this.b
//{...}
//Not this
this.c = this.a + this.b

I found here and in Vue forums ways to improve this code:
If you need to watch a data with multiple dependencies, you can do the next:

computed: {
    multi(){
        return [this.a, this.b].join()
    }
},
watch: {
    multi: {
        handler(): {
            this.c = this.a + this.b
        }
    }
}

I thing the best I can find solution was:

created(){
    this.$watch(
        (this) => (vm.x, vm.y, vm.z, Date.now()),
        function () {
            // Executes if `x`, `y`, or `z` have changed.
        }
    )
}

This last also return the function unwatch(), it stop the watcher property, if I do this.watcher = this.$watch(/*data and callback here*/), then I can do this.watcher() stop watcher and make new one, perfect for improve performance of this code.

Leave a comment