I am seeking to capture the @click event in JavaScript to dynamically create a DOM element in Vue.js (or Nuxt.js)

HTML

<button @click="createEle()" id="btn1">click</button>

vue

methods: {
   createEle() {
      let aEle = document.createElement("a")
      aEle.classList.add("btn2")
      aEle.innerHTML = "Button 2";
      document.body.appendChild(aEle)
   },
   getBtn2() {
      console.log(document.querySelector('.btn2').innderHTML)
   }
}

result my code after click Button #btn1

<button id="btn1">click</button>
<a class="btn2">Button 2</a>

but How to add the @click event to .btn2 to call the function getBtn2()

Answer №1

In this template:

   <button @click="createLink()" id="btn1">Click me</button>
   <a v-for="link in hyperlinks" :href="link.url" class="link-btn"&tg;{{link.text}}</a>

In the script section:

    data(){
      return {
          hyperlinks: [],
      }
    },
    methods:{
      createLink() {
        const newHyperlink = { url: "https://www.example.com/", text: "Example Site" };
        this.hyperlinks.push(newHyperlink);
      },
      displayLinks() {
         this.hyperlinks.forEach(item => console.log(item.text) );
      }
    }

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 to transfer an item in an array to another array using Vue JS

I'm diving into Vue.js for the first time and I have a simple online web store model in mind. I want to remove a product from the 'items list' array and add it to the 'cart list' array when a button is clicked by triggering the &ap ...

intervals should not be attached after being cleared by a condition

I am facing an issue with my slider that has a play button to change the slide image and a pause button. When I click on play, it functions as intended. However, when I pause and try to play again, it does not work. Although I clear the interval using th ...

Presenting information with Jqgrid

I have a value stored in an array variable called item which contains the following: var item = JSON.stringify(product); cartproduct[cartproduct.length] = item; The item variable stores data like this: { "Product": "1001", "Brand": "Dell", "Model" ...

Accessing attribute value of selected option in AngularJS select element

I have a select tag that displays options, and I want it so that when an option is selected, the value of the data-something attribute is copied into the input element. This is just for demonstration purposes; the actual value should be sent in the form. ...

Is there a method to prevent the json file from being constantly overwritten?

After running this code, I noticed that even when inputting a different userId, it still ends up overwriting the existing user instead of adding a new one as intended. const user = userId; const userObj = {[user]:valueX}; words.users = userObj; f ...

Issue with JQuery .when function occurring when not enclosed within a code block

Exploring the capabilities of the Beaker Browser API has led me to the need for making multiple (at least 20) ajax requests to extract content from another user's website. The essential arrays in play are: var posts = []; // Data from ajax requests ...

Encountered a POST Error while attempting to access a backend function from the frontend in a React application, resulting in

I have developed a website using React for the frontend and Node.js Express for the backend. However, I am facing an issue where calling a backend function from the frontend takes around 2 minutes and results in the following error being displayed in the c ...

Error encountered when attempting to destructure Object.entries() within a for-loop

Although I managed to get it to work, the perplexing part is trying to comprehend how this can occur! This error message pops up: [ReferenceError: Property ‘date’ doesn’t exist] for (const [date, items] of Object.entries(object)) { console.log(date) ...

Enhance your webpage by incorporating a CSS subclass using jQuery's addClass

Attempting to apply a subclass to a class using jQuery has proven tricky. The CSS in question is as follows: .block:nth-child(7) .permahover { top: 0 !important; left: 0 !important; opacity: 0; filter: alpha(opacity=0); -webkit-transform: t ...

The selected value is not displayed in the Material UI select component

My select component is showing the menu items and allowing me to select them, but it's not displaying the selected value. However, its handle function is functioning correctly because when I choose an item, the value in the database gets updated. Bel ...

showcasing recommended options in the search bar through the use of javaScript

Hey there, I've been working on creating result suggestions for my search bar. The generation process is all set, but I'm facing an issue with displaying the elements on the HTML page. During testing, I keep seeing ${resultItem.name}, and when I ...

Escaping double quotes in dynamic string content in Javascript can prevent unexpected identifier errors

Need help with binding the login user's name from a portal to a JavaScript variable. The user's name sometimes contains either single or double quotes. I am facing an issue where my JavaScript code is unable to read strings with double quotes. ...

Vite, Vue, and Vuetify: A multitude of inexplicable network requests happening

Excited to share that I've started working on my very first Vue project - a Simple CRUD Application. Utilizing Vite, Vue3, and Vuetify, with PNPM as the Package Manager. Development has been smooth so far, without encountering any major issues. Howev ...

Exploring the power of Mongoose.js and using the query object with Regular Expressions

In an application focused on locomotives, the search functionality queries models with specific metadata. To check against the keywords field, I need to include a regexp engine. My current approach is as follows: this.keywords = strings.makeSafe(this.par ...

Strategies for optimizing progressive enhancement

Designing a website that is accessible to everyone is truly an art form, and Progressive Enhancement is something I hold dear... I am curious to hear about the best techniques you have used to ensure websites work for all users, regardless of their browse ...

The page keeps scrolling to the top on its own, without any input from me

Whenever I reach the bottom of the page, my function loads new items seamlessly. However, an issue arises when the new items load, causing the scrolling position to abruptly return to the top of the page. This disrupts the user experience and is not the de ...

Converting a JSON array into a singular object using Node.js

I am struggling to convert a JSON array into a single object. Here are the details: Array: [{ "item-A": "value-1" }, { "item-B": "value-2" }] Expected Result: { "item-A": "value-1", "item-B": "value-2" } I have attempted various methods but none have yi ...

Extract an object array from the object and combine it into one cohesive unit

I am seeking assistance to consolidate data from an array of objects into a single array. Here is the current response I have: [ { "title": 'sample name of title 1', "isDeleted": false, "debates": [ ...

Adding fresh information to a data entity

I'm currently in the process of updating a data object with a new value. Upon checking, if the data associated with event.data.id exists within $("#ArticlesHolder"), I proceed to update it as follows: if($("#ArticlesHolder").data(event.data.id) != n ...

Watching a live video stream in real-time using WebRTC with React

Here is the HTML code <video ref={videos} autoPlay ></video> <Button onClick={() => navigator.mediaDevices.getUserMedia({audio: true, video: true}).then((mediaStream) => { videos.srcObject = mediaStream; videos.onloadedmetad ...