Understanding how to use Vuejs Components across multiple DOM elements, as well as how to initialize a Vue instance and utilize the "el

Imagine transitioning from the jQuery realm. If you are working with a component myPlugin (jQuery plug-in, such as a tool that displays tooltips when hovering over specific DOM elements) it would be initialized like this:

 $('.tooltipClass').myPlugin( { // options object here } )

This code will target all elements with the class tooltipClass and apply the myPlugin on them.

In Vue.js, the process is different and the documentation may not provide clear guidance. You have

let x = new Vue({
   el: '#app',
   ...
})

and according to the documentation:

Provide the Vue instance an existing DOM element to mount on. It can be a CSS selector string or an actual HTMLElement.

However, using a CSS selector could result in multiple elements (which doesn't work for multiple elements in Vue.js - as I've tested).

So, is there a way to replicate the jQuery initialization on multiple elements in Vue.js? (I understand one could do it manually outside of Vue.js)

The Vue.js documentation also lacks clarity on this issue. The version 3.x documentation omits the el option entirely, making it challenging to determine how to proceed in scenarios like the example mentioned above.

For instance, if you create a Vue.js popup component and need to display it when the user clicks on various buttons on the page. These buttons might have a role='popup' attribute in the HTML and trigger the customized popup (based on other data-xxx attributes, for example).

Such functionality is commonplace in modern JavaScript components. How can this be achieved with Vue.js?

Answer №1

To attach Vue to multiple elements, you will need to create multiple Vue instances:

document.querySelectorAll('.sampleClass').forEach(x => new Vue({el:x}));

It's important to remember that Vue operates differently than jQuery. Once a Vue instance is created, Vue will handle everything inside the element, so it's best to use Vue to create a complete component with all its behaviors rather than adding a single behavior to an existing element.

In the example of a popup, you should add an event listener using plain JavaScript and then create a Vue instance when the event is triggered for the popup.

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

Is there a way to update a single document in a MongoDB database using Mongoose without directly referencing the document?

Let's say I have an example: 1 //Let's say I have an example 2 3 app.post('/update', validate, async (req, res) => { 4 const {title, description, post_id} = req.body; 5 6 // Updating one of them if they exist 7 ...

Issue arose when attempting to pass parameters using the AJAX POST method to a C# MVC controller

Greetings fellow developers, I've been wrestling with a tricky ajax POST method for quite some time now, and could really use some fresh perspectives. I have a JavaScript function that gathers an array of strings to package up and send to one of my co ...

Adjusting the appearance of a JavaScript element based on its hierarchy level

Currently, I am utilizing Jqtree to create a drag and drop tree structure. My main goal is to customize the appearance of the tree based on different node levels. Javascript Tree Structure var data = [ { name: 'node1', id: 1, chi ...

Obtaining an Array through a direct input on the command line

I am having trouble incorporating raw command line arguments in my Node.js application. When I try with simple variables, everything works as expected (node example.js variable) However, when I pass an array as an argument, it does not work properly (n ...

Converting JSON data into an array containing individual objects, and inserting a new item into each object

I've been working on retrieving data from a JSON file and successfully creating an array of objects. However, I am trying to add an item to each object in the array simultaneously. Check out my current code: var linklist = []; $.getJSON('links. ...

Guide to creating a synchronous wrapper for jQuery ajax methods

I've made the decision to switch from synchronous ajax calls to asynchronous ones due to lack of support in most modern browsers. My code is currently reliant on synchronous (and dynamic) ajax calls to client-side functions that must be completed befo ...

Executing a script within a pop-up menu with AJAX

Currently, I have a popup menu that opens and displays text. However, my goal is to attach a controller to the popup menu so that it can perform specific actions. For instance, I would like to create an edit profile popup that includes all the necessary in ...

What is the best way to include an action column containing 'edit' and 'delete' buttons in my table?

I am looking to enhance the table by adding an action column with delete and edit buttons. The table displayed in the following image is the output of the code provided below. It is necessary to include an action column in the table to enable actions such ...

Guide to snagging a cookie with a Chrome extension

I'm attempting to retrieve a cookie from a specific website using a Chrome extension, but as someone who has never created one before, I'm facing some challenges. Despite reading numerous tutorials, I haven't been successful in capturing the ...

Error in the code that I am unable to locate in JavaScript, HTML, and CSS

I need help creating a navbar that displays the active site using HTML and JS code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content=& ...

JS click event listener is failing to activate the function as intended

In an attempt to create a modal window, I am facing issues with adding a click event listener to a div that should modify the CSS style of another element. The goal is to change the display property from 'none' to 'border-box' when the ...

Encountered an error while trying to load a resource: the server returned a 404 (Not Found) status code while attempting to edit a form using

I am facing an issue with navigating to the correct path after editing a form in React. Following the update, the web page refreshes and unexpectedly logs me out of the site even though there are no errors detected during the process. The console displays ...

JSON geometry imported is not following the movement of the bones

After importing a model into my Three.js scene, I encountered an issue where the bones can be moved and rotated successfully, but the model's geometry does not follow these bone movements. For importing the JSON file and adding it to the scene, here ...

Embed the Nest API into your HTML5 code

My mobile HTML5 application includes a script in the index.html file. Nest.js (code below) Whenever I run my application, I encounter an error stating that Firebase is not defined. This is odd because the function seems simple: --> var dataRef = new ...

Including a variable in an array within a function

I'm encountering an issue with inserting a variable into my array. Below is the code snippet: var data = new Array(); google.load("feeds", "1"); function initialize() { var feed = new google.feeds.Feed("http://www.ntvmsnbc.com/id/24927681/device/r ...

Position the typography component to the right side

Is there a way to align two typography components on the same line, with one aligned to the left and the other to the right? I'm currently using this code but the components are aligned next to each other on the left side. const customStyles = makeSt ...

Why is the location search not staying centered after resizing the map on Google Maps?

I am currently working on integrating Angular with Google Maps. I need to add some markers along with location search functionality. Additionally, I am including location information in a form. When the addMarker button is clicked, a form opens and the map ...

The variable referenced is not defined, resulting in a TypeError

Having some trouble with my code.. function compare(string,pattern){ var patternUpper = pattern.toUpperCase(); // Convert pattern to uppercase var stringUpper = string.toUpperCase(); // Convert string to uppercase for(var i=0;i<stringUpper.length-1 ...

Utilizing Angular's ng-model directive in combination with the required

I am attempting to implement a basic input field using html5 "required". The input field utilizes placeholder text, so I want the initial value of the input to be blank. I have connected the input to an ng-model that is set as empty initially to display th ...

What should I choose: HTML with javascript or javascript with JSP?

Greetings, I am a newcomer to the world of dynamic web development. Despite my efforts in searching this site, I was unable to find anything similar to what I'm looking for. My goal is to create a password checker that ensures robustness and sufficie ...