Using Vue3 to set attributes on web components

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?

Answer №1

I came across a solution, maybe not the most elegant one but it gets the job done :)

Within my web component, the mounted hook selects the component:

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

Instead of emitting after selecting the date, simply set the attribute:

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

Answer №2

Imagine if you were able to interact with the HTMLElement associated with your shadow host and then utilize the "setAttribute" method on it. Assuming you have access to the shadowRoot within your component by using 'this', a possible solution could look something like this (https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/host):

const element = this.shadowRoot.host; // The HTMLElement linked to <custom-element />
element.setAttribute("attributeName", valueYouWantToSet);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for utilizing both the Element Selector and Class Selector in Jquery

I am working with a simple table that has TDs assigned either the 'PLUS' or 'MINUS' class. My goal is to use jQuery to implement functionality for collapsing all or expanding all. When the Expand All button is clicked, I need to chang ...

At what point are functions executed? What methods can I use to manage their execution?

Looking to make a simple call to an API using jQuery's $.get() function as a JS beginner. The issue I'm facing is that the function seems to be called randomly rather than where I expect it in my code. I am open to either doing everything inside ...

Can you please provide information on the specific type of decorator used in Vuex, known as the 'vuex-class' decorator

My TypeScript project has the 'no-implicit-any' rule enabled, but I'm facing challenges when it comes to defining types for all of the 'vuex-class' decorators. For instance, when importing the namespaced action @(namespace('f ...

retrieving data from identical identifiers within a loop

Within my while loop, I am retrieving various dates for each event. <?php while( have_rows('_event_date_time_slots') ): the_row(); ?> <div> <h3 class="date-<?php echo $post->ID?>" name="tttdate<?php e ...

Is there a substitute for useState in a Next.js server component?

With my static site at , the only interactive feature being the dark mode toggle, I understand that using useState is not feasible in a server component. export default function RootLayout({ children }: { children: React.ReactNode }) { const [darkMode, ...

Tips for creating a scale animation using HTML5 Canvas

I am currently developing a canvas whiteboard tool and I have reached the stage where I am focusing on implementing the Zoom In and Zoom Out feature. While the functionality is working fine, I would like to enhance it with smooth animations for scaling. H ...

Show text using AJAX when the form is submitted

I'm in the process of creating a basic form with a submit button (see below). My objective is to allow users to enter text into the input box, click submit, and have the page refresh while displaying the entered text in a div element. The user's ...

Looking to learn how to replicate data effortlessly with either javascript or jquery?

I am currently trying to figure out how close I am to successfully cloning this div. Honestly, I am a bit lost at this point and could really use some assistance. Should I consider using jQuery for this task? <div id="question20">20. Details of Chi ...

Using NPM in conjunction with a PHP/STATIC web site directory structure: A comprehensive guide

My PHP website has a file structure like this: / css/ js/ index.php When I run the following commands: npm init npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb8984849f989f998a9babdfc5dd">[email p ...

Bringing in JavaScript files from a Bootstrap theme to incorporate them into a Vue3 application

Incorporating Bootstrap 5, a HTML theme with a CSS bundle file, and separate JS bundle files (main JS bundle file and plugin bundle file) containing Bootstrap code base + custom template features into a Vue 3 project is my current objective. I aim to utili ...

From Vanilla Javascript to ES6 Spread Operator

I recently incorporated a script into my project that utilizes the ES6 spread operator to extract parameters from the URL. However, I encountered an issue when I realized that the project does not support ES6 syntax. While it is straightforward to apply t ...

Reverse a filter within an ng-repeat loop - AngularJS

I have a question that I haven't found the answer to yet. Here is the issue I'm facing: The JSON data I am working with has this structure: [{ "batch_queue_name": "Batch One", "start_date": "12/01/2016 10:18 P.M.", "end_date": "12/03/2016 ...

Creating an array of objects by utilizing another array - the process explained

I am looking to create a new array by pushing objects after checking the values in an existing array. Here are the conditions: var ar=['aa','cc','po'] var arr =[{name:"po"},{name:'aa'},{name:'cc'}]; Desi ...

Is there a way to retrieve the textFrame where the cursor is currently located?

While inputting text into a frame, I am looking to execute a script. I want this script to target the specific text frame where my cursor is located. How can I reference this particular textFrame using Javascript? ...

What is the optimal strategy for incorporating both useLazyQuery and useQuery within the Apollo-client based on specific conditions?

In the navigation menu, I have options for "foods" and "cakes." The Foods page displays a list of all food items url: /foods When the user clicks on cakes, they are redirected to /foods?food=cakes, which is essentially the same page as the foods above. ...

Delivering Background Videos with Node.JS

Apologies if my question seems off base or confusing, as I am not very knowledgeable in the world of nodejs. I have been comfortable using just plain PHP and Apache for a while until I discovered ZURB Foundation's stack with Handlebars and SASS, along ...

When implementing useFetch with onMounted in Nuxt3, data is not being fetched upon directly opening the link

In my project, I have implemented the useFetch function in the composition api to fetch data. The function is then called within the onMounted hook of components. Here is how it's done: Custom Composable: useShows.ts export function useShows(){ ...

What is the process for programmatically incorporating Vue 3 components?

Vue 3 no longer includes the Vue.extend() method, which means the example provided in this article won't work as intended: https://css-tricks.com/creating-vue-js-component-instances-programmatically/ I attempted to implement a solution from: https:// ...

The search filter in Angular is limited in its ability to search through the entire table

I am facing an issue with the search filter in my table. Currently, it only searches records from the current page but I need it to search through the entire table. How can I modify it to achieve this? <input type="text" placeholder="Search By Any..." ...

What are the steps to initiate a new project using the CLI on a Linux operating system

I've got a project up and running in Vue JS with Node JS installed. Now I want to create a new project using CLI. Do I need to install another version of Node JS for this new project? ...