Reactive Data Tracking in Vue with TypeScript
Change detection is a fundamental aspect of reactive frameworks like Vue. This challenge asks you to build a simplified change detection mechanism within a Vue component, allowing you to track and react to modifications of a specific data property. This is useful for triggering side effects, updating derived data, or performing other actions whenever a value changes.
Problem Description
You are tasked with creating a Vue component that monitors a reactive data property (trackedValue) and emits a custom event (value-changed) whenever its value changes. The component should:
- Accept a
trackedValueprop: This prop will be the data property you want to monitor. It should be reactive (e.g., defined usingreforreactivein Vue's Composition API). - Track changes: The component must detect when the
trackedValuechanges. - Emit a
value-changedevent: When a change is detected, the component should emit avalue-changedcustom event. The event should carry the new value oftrackedValueas its payload. - Handle initial value: The component should not emit an event when it initially receives the
trackedValue. The event should only fire on subsequent changes. - TypeScript: The component must be written in TypeScript, ensuring type safety.
Expected Behavior:
The component should passively observe the trackedValue prop. It should not modify the value itself. It should only detect changes and emit the value-changed event accordingly.
Examples
Example 1:
Input: trackedValue = ref(10); (Initial value)
Output: No event emitted.
Explanation: The component receives the initial value and does not emit an event.
Example 2:
Input: trackedValue = ref(10);
trackedValue.value = 20;
Output: Emits 'value-changed' event with payload 20.
Explanation: The value of trackedValue changes from 10 to 20, triggering the event.
Example 3:
Input: trackedValue = reactive({ count: 5 });
trackedValue.count = 7;
Output: Emits 'value-changed' event with payload { count: 7 }.
Explanation: Even if the trackedValue is an object, changes to its properties should trigger the event with the new object.
Constraints
- The component must be written using Vue 3 and the Composition API.
- The component must be written in TypeScript.
- The
trackedValueprop can be of any type that is reactive in Vue (e.g.,ref,reactive). - The component should be performant; avoid unnecessary computations or DOM manipulations. The change detection should be efficient.
- The component should be reusable and not tightly coupled to any specific application logic.
Notes
- Consider using Vue's
watchfunction orwatchEffectto monitor thetrackedValueprop. - Remember to handle the initial value correctly to avoid emitting an event unnecessarily.
- Think about how to handle different data types for
trackedValue(primitive types, objects, arrays). The event payload should accurately reflect the new value. - Focus on creating a clean, readable, and well-typed component.