Maintain Unidirectional Data Flow#
Everyone knows that Vue has a unidirectional data flow, where child components cannot directly modify the props passed from parent components. However, when we encapsulate components using v-model, we might inadvertently break the rules of unidirectional data flow, as shown below:
v-model Implementation Principle#
Directly modifying the value of props in the child component breaks the unidirectional data flow. So what should we do? Let's first look at the implementation principle of v-model:
Emit Notification to Parent Component to Modify Prop Value#
Therefore, we can use emit. When the value of the child component changes, it does not directly modify the props but notifies the parent component to modify that value!
When the child component's value changes, it triggers the parent's update event and passes the new value. The parent component updates msg to the new value, as shown in the code below:
This is also the method most developers use to encapsulate components to modify values. In fact, there is another solution, which is to use computed properties' get and set.
Computed Intercepting Prop#
Most students use computed properties with get, and some may not even know that computed properties also have set. Let's look at the implementation method:
v-model Binding Objects#
What if v-model is binding to an object?
It can intercept multiple values like this:
This can meet our needs, but manually intercepting each property value of the v-model object is too cumbersome. If there are 10 inputs, we would need to intercept 10 times, so we need to consolidate the interceptions!
Listening to the Entire Object#
This looks perfect, but when we alert(123) in the set, it does not execute!!
The reason is: form.xxx = xxx does not trigger the computed set; only form = xxx will trigger the set.
Proxy Proxy Object#
So, we need to find a way to emit("update", newValue); when the properties of form are modified. To solve this problem, we can use Proxy.
Thus, we have perfectly intercepted the v-model object using Proxy + computed!
Then, for convenience in future use, we directly encapsulate it into a hook.
Original article link: https://juejin.cn/post/7277089907974422588
This article is synchronized and updated to xLog by Mix Space. The original link is https://liu-wb.com/posts/default/computed-intercepts-v-model