Is there a way to scan the DOM for a particular element and initiate a fresh Vue Instance?

I'm trying to come up with a method to scan the DOM for a specific element that has a class name of 'amp'. Once found, I would like to create a new Vue instance and utilize the data attributes in the HTML as values for data(). Would a loop be necessary for this task?

Is this achievable and what would be the recommended approach?

Thank you.

Sample HTML:

<div class="amp" id="vue" data-contentDeliveryUrl="www.urlexample.com" data-encodedQuery="=query234" data-cidItem="555-555-555"></div>

<div class="amp" id="vue" data-contentDeliveryUrl="www.urlexample.com" data-encodedQuery="=query123" data-cidItem="666-666-666"></div>

index.js

Illustration of a new instance

new Vue({
 el: '#vue',
 data() {
    return {
        contentDeliveryUrl: contentDeliveryUrl,
        encodedQuery: encodedQuery,
        cidItem: cidItem
    }
 },
 render: h => h(Page)
})

Answer №1

If you want to find elements with the amp class, you can utilize document.querySelectorAll to retrieve a NodeList containing those elements. Then, you can loop through this list to initiate Vue instances.

In order to assign values to Vue data properties, you should make use of the spread operator in combination with el.dataset. Your HTML data attributes must be hyphenated instead of using camel case.

(function() {
  document.querySelectorAll('.amp').forEach(el => {
    new Vue({
      el,

      data() {
        return {
          ...el.dataset,
        }
      },

      mounted() {
        console.log(this.$data)
        // this.contentDeliveryUrl
        // this.encodedQuery
        // this.cidItem
      },
    })
  })
})()
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="amp" id="vue" data-content-delivery-url="www.urlexample.com" data-encoded-query="=query234" data-cid-item="555-555-555"></div>

<div class="amp" id="vue" data-content-delivery-url="www.urlexample.com" data-encoded-query="=query123" data-cid-item="666-666-666"></div>

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

The property linerGradiant of r cannot be destructured because it is not defined

I encountered the error "Cannot destructure property linerGradiant of r as it is undefined" during runtime, making it difficult to debug. The issue seems to stem from the compiled JS file, which is hard to read. The function is defined as follows: functio ...

State not getting updated with array passed to this.setState()

Within an array, I have stored the following credentials: //The Snippet variable is an array that looks like this { details: test, _id: "5d9d0b506ee7d03a54d8b1f6", name: "TEST GREEN", content: "<div style="background-color:green; height:100px; widt ...

Is it possible to programmatically include a getter method to a class in JavaScript or TypeScript?

My current focus is on TypeScript and I'm exploring the decorators functionality. I would greatly appreciate some guidance or expert knowledge on JavaScript capabilities in this area. I am curious about dynamically adding a getter method to a Prototy ...

Retrieving information from an ajax array in PHP

I am currently attempting to retrieve an array of data using AJAX on the PHP side, but I am facing difficulties in accessing the values in PHP. Here is my JavaScript code snippet: console.log(obj); $.ajax({ method: 'POST', url: '/in ...

Display loading spinner in Material-UI Table while fetching data

Is it possible to display a Circular progress indicator while waiting for data to populate the table? How can this be accomplished? Currently, the table shows No records to display until the data is retrieved from the server. https://i.stack.imgur.com/Ljq ...

C# implementation of the btoa function from JavaScript

I am in need of assistance recoding a JavaScript function to C# that makes use of the btoa method to convert a string of Unicode characters into base64. The challenge lies in ensuring that the encoding used in both languages is identical, as currently, the ...

Automatically adjust text size within div based on width dimensions

Dealing with a specific issue here. I have a div that has a fixed width and height (227px x 27px). Inside this div, there is content such as First and Last name, which can vary in length. Sometimes the name is short, leaving empty space in the div, but som ...

Troubleshooting a Basic jQuery Validation Problem

I've been attempting to incorporate the "Refactoring rules" segment from http://jqueryvalidation.org/reference/ However, I'm struggling to figure out the appropriate placement for the $.validator code. Currently, I'm inserting it like this: ...

Centering the scrollIntoView feature on mobile devices is presenting challenges with NextJS applications

Description While navigating on mobile browsers, I'm facing a challenge with keeping an element centered as I scroll due to the browser window minimizing. I've experimented with different solutions such as utilizing the react-scroll library and ...

Unable to transmit an object using ExpressJS

Greetings. I am currently trying to comprehend ExpressJS. My goal is to send a simple object from the express server, but it only displays "cannot get" on the screen. app.get("/", (req, res, next) => { console.log("middleware"); const error = true; ...

Utilizing AngularJS: Employing the $q Promise Feature to Await Data Readiness in this Scenario

I am currently facing an issue with my Controller and Factory. The Controller initiates an API call in the Factory, but I am struggling to make it wait for the data to be gathered before proceeding. This is where I believe implementing something like $q mi ...

Error TS7053 indicates that an element is implicitly assigned the 'any' type when trying to use a 'string' type to index a 'User_Economy' type

Struggling with a particular question, but can't seem to find a solution. Error: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User_Economy'. No ind ...

Automatically navigate to a specific selection within the Autocomplete feature

Imagine having a dropdown or Autocomplete list in Material-UI with a long list of items. How can you make the list automatically scroll to a specific item when you open the dropdown? For instance, if we take the list of top100Films, the initial displayed i ...

Issue encountered while executing a freshly created VUE JS Hello.world application

My journey into app development begins with creating my first app using CLI: vue create hello-world. Upon attempting to launch the app using npm run serve in the CLI, it runs successfully. However, when I try to start it with npm run dev, an error is throw ...

Generate steps using Material UI/React Stepper to create organized pages (similar to Table Pagination)

As I venture into using Material UI along with React, my goal is to create organized "pages" consisting of steps in sets of four for a specific process. My initial attempt displayed all 10 steps on a single view, despite having the pagination correctly ca ...

Top method for cycling through an Array in React

I am looking to create a memory game using React for a portfolio project. I have an array of 20 items with 10 different sets of colors. const data = [ // Manchester Blue { ID: 1, Color: "#1C2C5B" }, ...

Verification of unique custom string

How can I ensure that a string follows the specific format of x.xx.xxxxx? The first character is mandatory, followed by a period, then two characters, another period, and finally any number of characters of varying lengths. ...

Transmit and exchange events between two JavaScript files within a node.js environment

Having some trouble getting EventEmitter to work in both directions between two Javascript files. In my server.js file: let api = require('./api') // Not working api.on("yo", data => { console.log(data) }) // Working api.emit("ready", "S ...

The FindProxyForURL function in a pac (proxy-auto-config) file is not compatible with the IE browser

After struggling for three days, we are still unable to solve a peculiar technical issue and now seek your assistance. The PAC (Proxy Auto-Config) file we have created works flawlessly in all browsers except for Internet Explorer (IE). The URL in questio ...

Creating Unique Identifiers in ExpressJS

I am currently utilizing mongoose to display admin and user information on a dashboard, but I am encountering difficulty rendering the id of a user. Below is the code I am using: function ensureAuthenticated(req, res, next){ if(req.isAuthenticated()){ ...