-
-
Notifications
You must be signed in to change notification settings - Fork 33.8k
Description
What problem does this feature solve?
I absolutely cannot imagine that nobody has brought this up before, but search hasn't delivered anything, so here's my take on the topic:
First of all, I love the concept of Computed Properties. So much. ❤️
However, there's one implementation detail in them that bugs me from time to time:
Computed Properties are often pretty simple calculations or string concatenations, and I find it tedious to have them always cover up three lines of code. (One for the property name, one for the implementation, one for the closing curly brace. You can of course put that in one line, but it usually makes the implementation looks less obvious / rather confusing.)
Arrow functions are an elegant solution to those simple mappings, but, as we all know, they're not applicable to Computed Properties because of their different this context.
What does the proposed API look like?
Since Computed Properties currently don't take any arguments, it would be relatively cheap (regarding implementation effort and possible BC changes) to not only bind their this context to the according Vue instance, but also pass it as a parameter.
Basic Example
It would allow for elegant solutions like this:
new Vue({
data: {
firstName: 'John',
lastName: 'Doe'
},
computed: {
fullName: vm => `${vm.firstName} ${vm.lastName}`
}
})Or even:
fullName: ({ firstName, lastName }) => `${firstName} ${lastName}`Getters / Setters
The only point where I could see this API getting slightly ugly are Computed Property setters, as they already receive a parameter and would have to take the vm as the second argument (to avoid breaking changes).
Getters / setters could be omitted from this topic entirely (i.e. staying unchanged) as they are usually not that concise anyway. However, for consistency I'd propose to have them receive the Vue instance as well, in the setter as the second argument:
fullName: {
get: vm => `${vm.firstName} ${vm.lastName}`,
set: (newValue, vm) => {
// Not of the greatest value here, we could just use a regular function and `this`
const names = newValue.split(' ')
vm.firstName = names[0]
vm.lastName = names[names.length - 1]
}
}Conclusion
As far as I can tell, this whole approach should not break any existing code.
Unfortunately it's not a feature available for userland implementation, that's why I felt it would be appropriate for a feature request.
I'd love to hear your thoughts about this. 🙂