Search code examples
javascriptvue.jsvuejs3web-component

Vue3 web component set attribute


I created stand alone web component, with Vite and Vue3, to replace old jQuery libraries.

When rendered in html, it looks something like:

<custom-datepicker id="deliveryTime">
  #shadow-root
  <div>...actual component...</div>
</custom-datepicker>

When user select date it would be perfect if I can set attribute value to this element, like:

<custom-datepicker value="selected value HERE" ...

so the form can then use this value from the element by it's id.

Problem is that the only way I manage to achieve this is by emitting event (selected) from my web component and listening to that event, so the form can use value, like:

const datepicker = document.querySelector('#deliveryTime');
const dateSelected = (e) => {
  datepicker.value = e.detail.val;
}
window.addEventListener('selected', dateSelected);

If I set value attribute within web component, rest of the app (Apache Velocity template) can't access it because it is in the shadow-root:

<custom-datepicker id="deliveryTime">
  #shadow-root
  <div value="selected value is sadly HERE">...actual component...</div>
</custom-datepicker>

Is it even possible to achieve this from inside the web component (so I can omit listener)?


Solution

  • I found solution, maybe not the cleanest one but it works :)

    In my web-component, in mounted hook component is selected:

    const dp = ref(null)
    onMounted(() => {
      dp.value = document.querySelector("#deliveryTime");
    })
    

    After date is selected, instead of emitting just set attribute:

    dp.value.setAttribute('value', value)