I recently developed a self-contained web component using Vite and Vue3 to replace outdated jQuery libraries.
When this component is rendered in HTML, it appears like this:
<custom-datepicker id="deliveryTime">
#shadow-root
<div>...actual component...</div>
</custom-datepicker>
It would be ideal if I could set the value
attribute to this element when the user selects a date, as shown below:
<custom-datepicker value="selected value HERE" ...
This way, the form can easily retrieve this value from the element using its id for further processing.
The challenge arises when trying to accomplish this without the need to emit an event (selected
) from the web component and have a listener handle it. The current workaround involves:
const datepicker = document.querySelector('#deliveryTime');
const dateSelected = (e) => {
datepicker.value = e.detail.val;
}
window.addEventListener('selected', dateSelected);
If the value attribute is directly set within the web component, other parts of the application (such as the Apache Velocity template) are unable to access it due to it being located in the shadow-root:
<custom-datepicker id="deliveryTime">
#shadow-root
<div value="selected value is sadly HERE">...actual component...</div>
</custom-datepicker>
This raises the question: Is there a way to achieve this functionality directly inside the web component itself, eliminating the need for external event listeners?