Provide data model API in addition to "writable computed" #756
Closed
zhangyx1998
started this conversation in
General
Replies: 1 comment
-
Upon second thought, this approach lacks generality and is hence unlikely to receive wide interest. I will close this thread. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Vue's
v-model
API has been very helpful to me since I came across it. However, when facing more complex use cases (such as input validation, data transformation, etc.), the implementation often becomes wordy and hard to understand.A possible solution to this (that's already available) is the writable computed API. Instead of a read-only proxy, it allows bidirectional data flow, hence could be used alongside v-model and provide more flexibility. Actually, the example given by the official documentation demonstrates one-to-many data binding.
However, after playing with it for a while, I realized that it only solves part of the problem I have in mind. To be specific:
The example given in the official doc lacks data validation, making the input box vulnerable to partial/malformed user input:
This problem is rather trivial, it can be fixed by wrapping the setter in a condition block that only executes if the input string passed validation.
Sometimes the input needs to be transformed/simplified before stored as an internal state. But the transformation should not be propagated back to user input box - this feels disruptive and confusing.
This is on longer trivial -- the data model should keep track of when the internal representation is still valid - and only overwrite it when the external reference changes.
Functionality of the "data model":
The data model standardizes the data validation process between certain type of user input and a set of internal states, ensuring the internal states are always validated (i.e. malformed states should not pass through). It also keeps an internal (intermediate) state that reflects the current user input. It feels like a ratchet connecting the user and internal data.
I created a demo at stackblitz playground. I added a graphical inspector for each example to help explain how the data model works. The demo implementation can be found at
src/model.ts
.Please let me know if this has been solved by an existing API/library that I am not aware of.
Thanks for reading!
Beta Was this translation helpful? Give feedback.
All reactions